Search code examples
phparraysgroupingassociative-arraytranspose

Restructure array data by chunking, transposing, and merging


I have array mentioned below, I will have value always multiple of 3.

$xyz = [
    ["name" => "abc"],
    ["name" => "snds"],
    ["name" => ""),
    ["number"=> "452"],
    ["number" => "845120"],
    ["number" => "84514513200"],
    ["email" => "ddddf"],
    ["email" => "dkskns"],
    ["email" => "kjnksdnkds"]
];

but this is not the proper format for me to perform further operations, so I want this array like mentioned below.

$abc = [
    [
        "name" => "abc",
        "number" => '452',
        "email" => "ddddf"
    ],
    [
        "name" => "snds",
        "number" => "845120",
        "email" => "dkskns"
    ],
    [
        "name" => "",
        "number" => "84514513200",
        "email" => "kjnksdnkds"
    ]
];

note: the array length is dynamic but it will always be multiple of 3


Solution

  • 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"
      }
    }