我的阵列正在咆哮
Array
(
[1] => Array
(
[9] => 6
[11] => 6
[12] => 6
[13] => 6
[14] => 12
)
[2] => Array
(
[4] => 8
[8] => 8
[13] => 13
)
)
我想要输出如下,有人可以帮助我这样做 我希望我总是将阵列分为两部分。
Array
(
[1] => Array
(
[1] => Array( [9] => 6
[11] => 6
)
[2] => Array( [12] => 6
[13] => 6
[14] => 12
)
)
[2] => Array
(
[1] => Array( [4] => 8
[8] => 8
)
[2] => Array( [13] => 13
)
)
)
答案 0 :(得分:2)
你可以试试这个 -
$new= array_map(function($v) {
$temp = array_chunk($v, 2); // break in chunks of 2
$final[]= array_shift($temp); // Take the first chunk out
$second= array();
foreach($temp as $t) {
$second = array_merge($second, $t); // merge the rest chunks
}
if(!empty($second)) {
$final[]= $second;
}
return $final;
}, $array);
答案 1 :(得分:1)
$res = [];
foreach($arr as $k => $v){
$lastdata = array_slice($v, 2,NULL,true);
$firstdata = array_chunk($v,2,true);
$res[$k]['1'] = $firstdata[0];
$res[$k]['2'] = $lastdata;
}
echo '<pre>'; print_r($res);
<强>输出强>: -
Array
(
[1] => Array
(
[1] => Array
(
[9] => 6
[11] => 6
)
[2] => Array
(
[12] => 6
[13] => 6
[14] => 12
)
)
[2] => Array
(
[1] => Array
(
[4] => 8
[8] => 8
)
[2] => Array
(
[13] => 13
)
)
)
希望它会对你有所帮助:)。
答案 2 :(得分:1)
$a=array('1'=>array('9'=>'6','11'=>'6','12'=>'6','13'=>'6','14'=>'12'),'2'=>array('4'=>'8','8'=>'8','13'=>'13'));
$res = array();
foreach($a as $k => $v){
$lastdata = array_slice($v, 2);
$firstdata = array_chunk($v,2,true);
$res[$k]['1'] = $firstdata[0];
$res[$k]['2'] = $lastdata;
}
echo '<pre>'; print_r($res);
检查截图
答案 3 :(得分:1)
您可以使用array_slice
$res = [];
foreach($arr as $key => $value){
$res[$key][1] = array_slice($value, 0, 2, true);
$res[$key][2] = array_slice($value,2, null, true);
}
var_dump($res);
输出:
Array
(
[1] => Array
(
[1] => Array
(
[9] => 6
[11] => 6
)
[2] => Array
(
[12] => 6
[13] => 6
[14] => 12
)
)
[2] => Array
(
[1] => Array
(
[4] => 8
[8] => 8
)
[2] => Array
(
[13] => 13
)
)
)
仅限PHP&gt; 5.2.4:changelog说:length参数的默认值更改为NULL。 NULL长度现在告诉函数使用数组的长度。在此版本之前,NULL长度表示零长度(不会返回任何内容)。