简体   繁体   English

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

[英]PHP Array: How to Inherit Key name from first Array value

I need to use PHP to get from this Array to the next Array, 我需要使用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"
                                )
                   )
          )

Please keep in mind that the array row has no set size or length. 请记住,数组row没有设置大小或长度。
Any help would be appreciated! 任何帮助,将不胜感激!
Thank you so much! 非常感谢!

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

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

}

array_fill_keys is a function in php. array_fill_keys是php中的函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM