i have the below outputted PHP array by using var_dump($fields);
array() {
[ 0 ] => array() {
[ "state" ] => string( 3 ) "nsw"
[ "address" ] => string( 13 ) "8 Test Street"
[ "phone" ] => string( 12 ) "0000 000 000"
[ "email" ] => string( 15 ) "info@123.com.au"
}
[ 1 ] => array() {
[ "state" ] => string( 2 ) "wa"
[ "address" ] => string( 13 ) "5 Test Street"
[ "phone" ] => string( 12 ) "0000 000 000"
[ "email" ] => string( 15 ) "info@123.com.au"
}
[ 2 ] => array() {
[ "state" ] => string( 3 ) "qld"
[ "address" ] => string( 13 ) "3 Test Street"
[ "phone" ] => string( 12 ) "0000 000 000"
[ "email" ] => string( 15 ) "info@123.com.au"
}
[ 3 ] => array() {
[ "state" ] => string( 3 ) "nsw"
[ "address" ] => string( 13 ) "1 Test Street"
[ "phone" ] => string( 12 ) "0000 000 000"
[ "email" ] => string( 15 ) "info@123.com.au"
}
}
I would like to create a new array from all "state" keys present in $fields and shift corresponding values over so its like the below.
array() {
[ "nsw" ] => array() {
[0] => array() {
[ "address" ] => string( 13 ) "8 Test Street"
[ "phone" ] => string( 12 ) "0000 000 000"
[ "email" ] => string( 15 ) "info@123.com.au"
}
[1] => array() {
[ "address" ] => string( 13 ) "1 Test Street"
[ "phone" ] => string( 12 ) "0000 000 000"
[ "email" ] => string( 15 ) "info@123.com.au"
}
}
[ "wa" ] => array() {
[0] => array() {
[ "address" ] => string( 13 ) "5 Test Street"
[ "phone" ] => string( 12 ) "0000 000 000"
[ "email" ] => string( 15 ) "info@123.com.au"
}
}
[ "qld" ] => array() {
[0] => array() {
[ "address" ] => string( 13 ) "3 Test Street"
[ "phone" ] => string( 12 ) "0000 000 000"
[ "email" ] => string( 15 ) "info@123.com.au"
}
}
}
Can anyone please help, been searching for an answer on this with no luck.
Thanks!
just a little bit logic.
<?php
$fields = [
[
"state" => "nsw",
"address" => "8 Test Street",
"phone" => "0000 000 000",
"email" => "info@123.com.au",
],
[
"state" => "wa",
"address" => "5 Test Street",
"phone" => "0000 000 000",
"email" => "info@123.com.au",
],
[
"state" => "qld",
"address" => "3 Test Street",
"phone" => "0000 000 000",
"email" => "info@123.com.au",
],
[
"state" => "nsw",
"address" => "1 Test Street",
"phone" => "0000 000 000",
"email" => "info@123.com.au",
]
];
$new = [];
foreach ($fields as $field) {
$state = $field['state'];
unset($field['state']);
$new[$state][] = $field;
}
print_r($new);
Array
(
[nsw] => Array
(
[0] => Array
(
[address] => 8 Test Street
[phone] => 0000 000 000
[email] => info@123.com.au
)
[1] => Array
(
[address] => 1 Test Street
[phone] => 0000 000 000
[email] => info@123.com.au
)
)
[wa] => Array
(
[0] => Array
(
[address] => 5 Test Street
[phone] => 0000 000 000
[email] => info@123.com.au
)
)
[qld] => Array
(
[0] => Array
(
[address] => 3 Test Street
[phone] => 0000 000 000
[email] => info@123.com.au
)
)
)
This should do it neatly.
$grouped = array_reduce($addresses, function ($grouped, $address) {
return array_merge_recursive($grouped, [
$address['state'] => [ $address ],
]);
}, []);