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?

+3


source to share


3 answers


Try to reassign the value c

:

$data['c'] = array_values($data['c']);

      



It will reindex your array c

, but the indices start at 0

. If you really want to start with 0

, try:

$data['c'] = array_combine(range(1, count($data['c'])), array_values($data['c']))

      

+4


source


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']);

      

+2


source


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
}

      

+1


source







All Articles