分解数组元素的每个值
Explode each values of Array element
我有一个像这样的数组:
Array
(
[2] => 2,6
[3] => 1
[4] => 14
[5] => 10
[6] => 8
)
我想使用 array_map 分解数组的每个元素和 return 一个新数组,这样我就可以避免使用循环,并创建额外的函数来回调。
O/p 应该像:
Array
(
[2] => Array
(
[0] => 2
[1] => 6
)
[3] => Array
(
[0] => 1
)
[4] => Array
(
[0] => 14
)
[5] => Array
(
[0] => 10
)
[6] => Array
(
[0] => 8
)
)
试试下面的代码
$newArr = array_map(function($val, $key){
return explode(",", $val);
}, $arr);
您可以使用
$result = array_map(function($val) {
return explode(',', $val);
}, $input);
这将导致
Array
(
[2] => Array
(
[0] => 2
[1] => 6
)
[3] => Array
(
[0] => 1
)
[4] => Array
(
[0] => 14
)
[5] => Array
(
[0] => 10
)
[6] => Array
(
[0] => 8
)
)
这将适用于 PHP >= 5.3,支持匿名函数。
$data = array(2 => '2,6',3 => '1',4 => '14',5 => '10',6 => '8');
foreach($data as $key => $val) {
$new = explode(',',$val);
$data[$key] = $new;
}
$output = $data;
echo '<pre>';
print_r($output);
你也可以
$result = array_map('str_getcsv', $input);
这也会导致
Array
(
[2] => Array
(
[0] => 2
[1] => 6
)
[3] => Array
(
[0] => 1
)
[4] => Array
(
[0] => 14
)
[5] => Array
(
[0] => 10
)
[6] => Array
(
[0] => 8
)
)
我有一个像这样的数组:
Array
(
[2] => 2,6
[3] => 1
[4] => 14
[5] => 10
[6] => 8
)
我想使用 array_map 分解数组的每个元素和 return 一个新数组,这样我就可以避免使用循环,并创建额外的函数来回调。
O/p 应该像:
Array
(
[2] => Array
(
[0] => 2
[1] => 6
)
[3] => Array
(
[0] => 1
)
[4] => Array
(
[0] => 14
)
[5] => Array
(
[0] => 10
)
[6] => Array
(
[0] => 8
)
)
试试下面的代码
$newArr = array_map(function($val, $key){
return explode(",", $val);
}, $arr);
您可以使用
$result = array_map(function($val) {
return explode(',', $val);
}, $input);
这将导致
Array
(
[2] => Array
(
[0] => 2
[1] => 6
)
[3] => Array
(
[0] => 1
)
[4] => Array
(
[0] => 14
)
[5] => Array
(
[0] => 10
)
[6] => Array
(
[0] => 8
)
)
这将适用于 PHP >= 5.3,支持匿名函数。
$data = array(2 => '2,6',3 => '1',4 => '14',5 => '10',6 => '8');
foreach($data as $key => $val) {
$new = explode(',',$val);
$data[$key] = $new;
}
$output = $data;
echo '<pre>';
print_r($output);
你也可以
$result = array_map('str_getcsv', $input);
这也会导致
Array
(
[2] => Array
(
[0] => 2
[1] => 6
)
[3] => Array
(
[0] => 1
)
[4] => Array
(
[0] => 14
)
[5] => Array
(
[0] => 10
)
[6] => Array
(
[0] => 8
)
)