change php array format

点点圈 提交于 2019-12-11 12:54:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!