标签:blog http io ar for sp on 2014 art
前不久,自己在一个小项目上,想取出一个二维数组每个元素的一个key的值,组成一个一维数组,突然想到了php 中有个函数可以实现.
$array = array ( array ( "id" => 12, "name" => "Karl" ), array ( "id" => 4, "name" => "Franz" ), array ( "id" => 9, "name" => "Helmut" ), array ( "id" => 10, "name" => "Kurt" ) ); print_r(array_column($array, 'id'));
但出错了,网页上错误提示是 no function 没有这个函数,但手册是有的,为什么呢?打开手册才知道是php 5.5新增的,而我的php版本确实 php 5.3所以没有,如何解决了.于是我写了
下面两种算法
第一种算法如下所示:
$key = 'id'; $array = array ( array ( "id" => 12, "name" => "Karl" ), array ( "id" => 4, "name" => "Franz" ), array ( "id" => 9, "name" => "Helmut" ), array ( "id" => 10, "name" => "Kurt" ) ); $ar = array_map ( function ($element) use($key) { $newarray = array (); if (array_key_exists ( $key, $element )) { $newarray = $element [$key]; } return $newarray; }, $array ); print_r ( $ar );
上面有个函数 function ($element) use ($key) 结构 请访问 点击打开链接
第二种方法是:
function array_merge_on_key($key, $array1, $array2) { $arrays = array_slice(func_get_args(), 1); $r = array(); foreach($arrays as &$a) { if(array_key_exists($key, $a)) { $r[] = $a[$key]; continue; } } return $r; } // example: $array1 = array("id" => 12, "name" => "Karl"); $array2 = array("id" => 4, "name" => "Franz"); $array3 = array("id" => 9, "name" => "Helmut"); $array4 = array("id" => 10, "name" => "Kurt"); $result = array_merge_on_key("id", $array1, $array2, $array3, $array4); print_r($result);
不过我是特别喜欢用数组函数 array_map()这种结构的.
标签:blog http io ar for sp on 2014 art
原文地址:http://blog.csdn.net/xingjigongsi/article/details/40481293