PHP数组:如何从第一个Array值继承键名

时间:2011-03-04 11:54:16

标签: php arrays json key

我需要使用PHP从这个数组转到下一个数组,

      [results] => Array
          (
              [row] => Array
                  (
                           [0] => Array
                                (
                                    [col0] => "banana"
                                    [col1] => "grape"
                                    [col2] => "apple"
                                )

                            [1] => Array
                                (
                                    [col0] => "ford"
                                    [col1] => "chevy"
                                    [col2] => "chrysler"
                                )
                   )
          )

      [results] => Array
          (
              [row] => Array
                  (
                           [banana] => Array
                                (
                                    [col0] => "banana"
                                    [col1] => "grape"
                                    [col2] => "apple"
                                )

                            [ford] => Array
                                (
                                    [col0] => "ford"
                                    [col1] => "chevy"
                                    [col2] => "chrysler"
                                )
                   )
          )

请注意,数组row没有设定的大小或长度 任何帮助将不胜感激! 非常感谢!

4 个答案:

答案 0 :(得分:4)

$data = array(...); // your data
foreach ( $data['results']['row'] as $k => $v ) {
  unset($data['results']['row'][$k]);
  $data['results']['row'][$v['col0']] = $v;
}

答案 1 :(得分:0)

$new_array = array();
foreach ($array as $key => $value) {
    foreach ($value as $key2 => $value2) {
         $new_array[$key][$key2][$value2['col0']] = $value2;
    }
}

var_dump($new_array);

答案 2 :(得分:0)

$farray = array(); //your array
foreach($faray['results']['row'] as $key => $val)
{
    echo $key;
    echo '<hr>';
    print_r($val);
    echo '<br>';

}

答案 3 :(得分:0)

array_fill_keys是php中的一个函数。

参考http://www.php.net/manual/en/function.array-fill-keys.php