【问题标题】:Dynamic array key in while loopwhile循环中的动态数组键
【发布时间】:2010-02-18 15:08:59
【问题描述】:

我正在努力解决这个问题:

我有一个数组,每个循环都会“更深”。我需要向最深的“子”键添加一个新数组。

while($row = mysql_fetch_assoc($res)) {
    array_push($json["children"],
                        array(
                            "id" => "$x",
                            "name" => "Start",
                            "children" => array()
                        )
                    );
}

所以,在一个循环中它会是:

array_push($json["children"] ...
array_push($json["children"][0]["children"] ...
array_push($json["children"][0]["children"][0]["children"] ...

... 等等。关于如何获得这样的键选择器动态的任何想法?

$selector = "[children][0][children][0][children]";
array_push($json$selector);

【问题讨论】:

    标签: php multidimensional-array


    【解决方案1】:
    $json = array();
    $x = $json['children'];
    while($row = mysql_fetch_assoc($res)) {
        array_push($x,
                    array(
                        "id" => "$x",
                        "name" => "Start",
                        "children" => array()
                    )
                );
        $x = $x[0]['children'];
    }
    print_r( $json );
    

    【讨论】:

      【解决方案2】:

      嗯——也许最好通过引用来分配:

      $children =& $json["children"];
      while($row = mysql_fetch_assoc($res)) {
          array_push($children,
              array(
                  "id" => "$x",
                  "name" => "Start",
                  "children" => array()
              )
          );
          $children =& $children[0]['children'];
      }
      

      【讨论】:

        【解决方案3】:
        $json = array();
        $rows = range('a', 'c');
        foreach (array_reverse($rows) as $x) {
            $json = array('id' => $x, 'name' => 'start', 'children' => array($json));
        }
        print_r($json);
        

        如果您想通过字符串路径读取数组,请将字符串拆分为索引,然后您可以执行类似的操作来获取值

        function f($arr, $indices) {
            foreach ($indices as $key) {
                if (!isset($arr[$key])) {
                    return null;
                }
                $arr = $arr[$key];
            }
            return $arr;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-06
          • 2020-10-28
          • 1970-01-01
          • 1970-01-01
          • 2010-10-26
          • 1970-01-01
          相关资源
          最近更新 更多