将两个二维数组中两相同key下的值合并
$a = array( array ( 'id' => 1, 'catid' => 6));
$b = array( array ( 'title' => '标题', 'content' => '内容'));
//打印数据
print_r(array( $a[0]+$b[0]) );
print_r(array( array_merge($a[0], $b[0]) ));
print_r(array_map('array_merge', $a, $b));
都可以得到
Array(
[0] => Array(
[id] => 1
[catid] => 6
[title] => 标题
[content] => 内容
)
)
array_column返回数组中某个单一列的值。简化代码可少用foreach
array_reduce用回调函数迭代地将数组简化为单一的值:
#array_column和array_reduce组合使用
$serverList=array(3) {
[1]=>
array(1) {
["info"]=>
string(58) "{"id":1,"ip":"192.168.1.1","zone":10,"dns":"www.test.com"}"
}
[2]=>
array(1) {
["info"]=>
string(58) "{"id":2,"ip":"192.168.1.2","zone":50,"dns":"www.test.com"}"
}
[3]=>
array(1) {
["info"]=>
string(58) "{"id":3,"ip":"192.168.1.3","zone":40,"dns":"www.test.com"}"
}
}
//这种情况不使用foreach拿出每个info中的ip
//create_function是匿名函数,可以把$v理解成返回的结果值,$w 理解为第二层数组
$arr = array_reduce($serverList, create_function('$v,$w', '$v[]=json_decode($w[info],true);return $v;'));
$ipInfo=array_column($arr, 'ip');
var_dump($ipInfo);
输出:
array(3) {
[0]=>
string(11) "192.168.1.1"
[1]=>
string(11) "192.168.1.1"
[2]=>
string(11) "192.168.1.1"
}
array_search搜索数组中的值,返回对应的键
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);