PHP数组可读[关闭]
问题描述:
I have an Array format.
Array
(
[0] => Array
(
[order_id] => 1
)
[1] => Array
(
[order_id] => 11
)
[2] => Array
(
[order_id] => 12
)
)
It should to be changed the array format to be like this format:
[1,11,12];
Please help. Thank you in advanced.
答
For (PHP 5 >= 5.5.0, PHP 7) you can use array_column
and lower than that you can use array_map
function (for PHP < 5.3) you need to define saperate function for array_map
instead of anonymous function.
$array = array
(
'0' => array
(
'order_id' => 1
),
'1' => array
(
'order_id' => 11
),
'2' => array
(
'order_id' => 12
)
);
$new_array = array_column($array, 'order_id');
print_r($new_array);
$new_array = array_map(function($element) {
return $element['order_id'];
}, $array);
print_r($new_array);
output
Array
(
[0] => 1
[1] => 11
[2] => 12
)
答
How about this?
$arr = Array
(
0 => Array
(
'order_id' => 1
),
1 => Array
(
'order_id'=> 11
),
2 => Array
(
'order_id' => 12
),
);
$newArr = array();
foreach($arr as $x){
foreach($x as $y){
$newArr[] = $y;
}
}
答
You can try this:
$ar = array(array('order_id' => 1), array('order_id' => 11), array('order_id' => 12));
$temp = array();
foreach ($ar as $val) {
$temp[] = $val['order_id'];
}
print_r($temp);
答
Basically, you are looking to flatten the array. This SO answer has some tips on how to do that. Also, there's a golf version in this Github gist.
For the specific case in your question, this should do
function specificFlatten($arr) {
if (!is_array($arr)) return false;
$result = [];
foreach ($arr as $arr_1) {
result[] = $arr_1['order_id'];
}
return $result;
}