问题
I have array mentioned below, I will have value always multiple of 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"));
but this is not the proper format for me to perform further operations, so I want this array like mentioned below.
$abc = array(array("name"=>"abc","number"=>'452',"email" => "ddddf"),array("name" => "snds","number" =>"845120","email" => "dkskns"),array("name" => "", "number" => "84514513200","email" => "kjnksdnkds"));
note: the array length is dynamic but it will always be multiple of 3
回答1:
One possibility could be to use the modulo % operator.
In the foreach the value is an array and you could use array_keys to get the key and reset to get the value of the first array element.
$result = [];
$count = 0;
foreach ($xyz as $value) {
if ($count%3 === 0) {
$count = 0;
}
$result[$count][array_keys($value)[0]] = reset($value);
$count++;
}
Demo
That will give you:
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"
}
}
回答2:
This will do:
$result = array_map('array_merge', ...array_chunk($xyz, count($xyz) / 3));
来源:https://stackoverflow.com/questions/50424385/change-php-array-format