将键值存储为php中的数组索引

时间:2017-09-19 07:50:39

标签: php

Theres中的一个数组,如下面的

Array
(

 [0] => Array
    (
        [int_city_id] => 1
        [txt_cityname] => Lucknow
        [time_stamp] => 2017-09-18 14:11:05
    )
  [1] => Array
    (
        [int_city_id] => 3
        [txt_cityname] => Kanpur
        [time_stamp] => 2017-09-14 12:09:46
    )


   )

需要像以下一样保存

  Array
(
        [1] => Lucknow
       ,
        [3] => Kanpur
   )

如何使用最佳方式在PHP中实现此目的

我试过了:

   foreach ($cities as $key => $value) {
     # code...
     $newarr[$value['int_city_id']]=$value['txt_cityname'];
   }
   print_r($newarr);

1 个答案:

答案 0 :(得分:0)

你可以使用这样的内置函数:

$newArray = array_combine(array_column($cities,'int_city_id'),
                          array_column($cities,'txt_cityname'));

然而,你为什么这样?既然你已经在foreach循环中使用$cities数组执行其他操作,为什么不在其中构建新数组呢?换句话说,没有错:

foreach ($cities as $index => $city) {
  # code...
  $newArray[$city['int_city_id']] = $city['txt_cityname'];
}

如果你经常使用$city的值,你可以先提取它们:

foreach ($cities as $index => $city) {
  extract($city,EXTR_PREFIX_ALL,'city');
  # code...
  $newArray[$city_int_city_id] = $city_txt_cityname;
}

它看起来更清晰,并且会稍微更快地执行构建新阵列的行,但只是很小的余量。当然extract()也需要时间,所以只有在重复使用$city的值时才这样做。