Home > Enterprise >  How do i merge these arrays into one
How do i merge these arrays into one

Time:07-15

I want to change the following php array

  "extra_charge_item" => [
    0 => "Massage",
    1 => "Pool table",
    2 => "Laundry"
  ],
  "extra_charge_description" => [
    0 => "Paid",
    1 => "Paid",
    2 => "We wash everything"
  ],
 "extra_charge_price" => [
    0 => "200",
    1 => "100",
    2 => "1000"
  ],

I haven't been able to solve for a whole 2hrs

This is the expected output

"new_data" => [
    0 => [
         "Maasage", "Paid", "200"
         ],
    1 => [
         "Pool table", "Paid", "100"
         ],
    2 => [
         "Laundry", "we wash everything", "1000"
         ]
  ]

CodePudding user response:

Rather than doing all the work for you, here's some pointers on one way to approach this:

  1. If you are happy to assume that all three sub-arrays have the same number of items, you can use array_keys to get those keys from whichever you want.
  2. Once you have those keys, you can use a foreach loop to look at each in turn.
  3. For each key, use square bracket syntax to pluck the three items you need.
  4. Use [$foo, $bar, $baz] or array($foo, $bar, $baz) to create a new array.
  5. Assign that array to your final output array, using the key from your foreach loop.

CodePudding user response:

Just use foreach with key => value

$data = [
    "extra_charge_item" => [
        0 => "Massage",
        1 => "Pool table",
        2 => "Laundry"
    ],
    "extra_charge_description" => [
        0 => "Paid",
        1 => "Paid",
        2 => "We wash everything"
    ],
    "extra_charge_price" => [
        0 => "200",
        1 => "100",
        2 => "1000"
    ],
];
$newData = [];
foreach ($data as $value) {
    foreach ($value as $k => $v) {
        $newData[$k][] = $v;
    }
}

var_dump($newData);
  • Related