我有下面提到的数组,我的值总是3的倍数。
$xyz = array(array('name'=>'abc'),array("name"=>"snds"),array("name"=>""),array("number"=>"452"),array("number"=>"845120"),array("number" => "84514513200"),array("email" => "ddddf"),array("email" => "dkskns"),array("email" => "kjnksdnkds"));
但这不是我执行进一步操作的正确格式,所以我想要这个数组如下所述。
$abc = array(array("name"=>"abc","number"=>'452',"email" => "ddddf"),array("name" => "snds","number" =>"845120","email" => "dkskns"),array("name" => "", "number" => "84514513200","email" => "kjnksdnkds"));
注意:数组长度是动态的,但它总是3的倍数
答案 0 :(得分:2)
一种可能性是使用modulo %
运算符。
在foreach
中,值是一个数组,您可以使用array_keys获取密钥,reset获取第一个数组元素的值。
$result = [];
$count = 0;
foreach ($xyz as $value) {
if ($count%3 === 0) {
$count = 0;
}
$result[$count][array_keys($value)[0]] = reset($value);
$count++;
}
那会给你:
array(3) {
[0]=>
array(3) {
["name"]=>
string(3) "abc"
["number"]=>
string(3) "452"
["email"]=>
string(5) "ddddf"
}
[1]=>
array(3) {
["name"]=>
string(4) "snds"
["number"]=>
string(6) "845120"
["email"]=>
string(6) "dkskns"
}
[2]=>
array(3) {
["name"]=>
string(0) ""
["number"]=>
string(11) "84514513200"
["email"]=>
string(10) "kjnksdnkds"
}
}
答案 1 :(得分:0)
这样做:
$result = array_map('array_merge', ...array_chunk($xyz, count($xyz) / 3));