Here's my array:
[a] => apple
[b] => banana
[c] => Array
(
[2] => x
[4] => y
[6] => z
)
I'm looking for a way to put my [c]
array variables in "order". Making my array, look like this:
[a] => apple
[b] => banana
[c] => Array
(
[1] => x
[2] => y
[3] => z
)
Is there a way to do it without creating a new function by myself?
Just try with reassigning c
value:
$data['c'] = array_values($data['c']);
It will reindex your c
array, but the indexes will start with 0
. If you really want to start with 0
, try:
$data['c'] = array_combine(range(1, count($data['c'])), array_values($data['c']))
Fortunately PHP provides a lot of functions for array sorting , you don't have to write another one.
Try sort($a['c'])
(assuming your array is stored in the $a variable).
$a = array(
'a' => 'apple',
'b' => 'banana',
'c' => array(
'1' => 'x',
'2' => 'y',
'3' => 'z',
),
);
sort($a['c']);
print_r($a);
The output:
Array
(
[a] => apple
[b] => banana
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)
If you don't need to sort the content of $a['c']
and only want to re-index it (let it have numeric consecutive keys starting with 0
) then array_values()
is all it needs:
$a['c'] = array_values($a['c']);
If you don't know how many arrays needs to be sorted, 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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.