我有一个如下所示的数组:
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 实现这种转换?
感谢所有帮助。
最简单的方法:(假设你希望它实际输出字符串
[5,6,...,2]
<?php
$ids=array();
foreach($yourArray as $k=>$v){
$ids[] = $v['id'];
}
$resultCsv = implode(',', $ids);
$result = '['.$resultCsv.']';
echo $result
?>
您可以处理数组的每个成员并将每个当前处理的子数组的成员“id”附加到新数组:
<?php
// code
foreach $array as $member {
$newarray[]=$member["id"];
}
// code
?>
您可以使用
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 example that would be $theArray)
$arrString = json_encode($theArray);