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:
- 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.
- Once you have those keys, you can use a foreach loop to look at each in turn.
- For each key, use square bracket syntax to pluck the three items you need.
- Use
[$foo, $bar, $baz]
orarray($foo, $bar, $baz)
to create a new array. - 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);