我有一个如下所示的数组:
Array ( [0] => Array ( [id] => 0 ) [1] => Array ( [id] => 0 ) [2] => Array ( [id] => 0 ) [3] => Array ( [id] => 0 ) [4] => Array ( [id] => 0 ) [5] => Array ( [id] => 0 ) [6] => Array ( [id] => 0 ) [7] => Array ( [id] => 0 ) [8] => Array ( [id] => 0 ) [9] => Array ( [id] => 0 ) [10] => Array ( [id] => 0 ) [11] => Array ( [id] => 4 ) [12] => Array ( [id] => 1 ) [13] => Array ( [id] => 2 ) [14] => Array ( [id] => 0 ) [15] => Array ( [id] => 0 ) [16] => Array ( [id] => 5 ) [17] => Array ( [id] => 1 ) )
我希望将其转换为以下格式:
[0,0,0,0,0,0,0,0,0,0,0,4,1,2,0,0,5,1]
如何使用php实现此转换?
感谢所有帮助。
答案 0 :(得分:2)
PHP> = 5.5.0或使用PHP Implementation of array_column():
array_column()
答案 1 :(得分:1)
您可以使用array_map
或array_walk
:
使用array_map
:
$new = array_map(function ($value) { return $value['id']; }, $theArray);
print_r($new);
使用array_walk
:
array_walk($theArray, function (&$value, $key) { $value = $value['id']; };
print_r($theArray);
这些之间的主要区别是array_map
生成一个全新的数组,并且您没有将密钥传递给回调函数。另一方面,array_walk
通过引用处理数组,并且回调也获得了密钥。
现在我不清楚你是否想要重组数组(我提供了解决方案),或者你想要它是否像你提供的[0,1,2,3,...]
这样的特定字符串格式。如果您确实需要字符串格式,那么您现在需要做的就是调用json_encode
:
// note if you used array_map pass the variable that holds the result of the call
// (in my example that would be $new); If you used array_walk then pass the same array
// you supplied as the argument to the call (in my exmaple that would be $theArray)
$arrString = json_encode($theArray);
答案 2 :(得分:1)
最简单的方法:(假设您希望它实际输出字符串[5,6,...,2]
<?php
$ids=array();
foreach($yourArray as $k=>$v){
$ids[] = $v['id'];
}
$resultCsv = implode(',', $ids);
$result = '['.$resultCsv.']';
echo $result
?>
答案 3 :(得分:1)
您可以处理数组的每个成员,并将每个当前处理的子数组的成员“id”附加到新数组:
<?php
// code
foreach $array as $member {
$newarray[]=$member["id"];
}
// code
?>