Put your array variables in order
Here's my array:
[a] => apple
[b] => banana
[c] => Array
(
[2] => x
[4] => y
[6] => z
)
I am looking for a way to put my array variables [c]
in "order". Array creation looks like this:
[a] => apple
[b] => banana
[c] => Array
(
[1] => x
[2] => y
[3] => z
)
Is there a way to do this without creating a new function for yourself?
source to share
Fortunately, PHP provides many functions for sorting arrays , you don't need to write another one.
Try it sort($a['c'])
(assuming your array is stored in $ a variable).
$a = array(
'a' => 'apple',
'b' => 'banana',
'c' => array(
'1' => 'x',
'2' => 'y',
'3' => 'z',
),
);
sort($a['c']);
print_r($a);
Output:
Array
(
[a] => apple
[b] => banana
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)
If you don't need to sort the content $a['c']
and only want to re-index it (let's say it has numeric sequential keys starting with 0
), then array_values()
this is all it needs:
$a['c'] = array_values($a['c']);
source to share
If you don't know how many arrays to sort, try this:
$testarr = ['a' => 'apple', 'b' => 'banana', 'c' => ['x', 'y', 'z']];
foreach ($testarr as $key => $item) {
if (is_array($item)) { $arr[$key] = array_values($item); }
// if (is_array($item)) { $arr[$key] = asort($item); } // use asort() if you want to keep subarray keys
}
source to share