patrick patrick - 1 year ago 174
PHP Question

sort object by integer key in PHP

I have an array with ID's as the key and a name from a database associated with it. I use this to get statistics from PHP for output to a Google Chart generated in JavaScript (through JSON). In PHP I have the following array:

$a = [
'33' => 'first',
'25' => 'second',
'14' => 'last

If I run the following code:

foreach( $a as $key => $val )
echo "$key => $val" . PHP_EOL;

I get the following (expected) result

33 => first
25 => second
14 => last

I use AJAX and JSON to send this to a JavaScript environment, here it becomes an object. Now when I run the following JavaScript:

for( var i in a )
console.log( i + " => " + a[i] );

I get

14 => last
25 => second
33 => first

so my keys are interpreted as integers and sorted in JavaScript, which in this case means the array with statistics I was sending to Google Chart is matching up with the wrong labels.

I solved this by sorting the array in PHP before I read the statistics from the database. I needed the keys to stay the same though, this is what I did in PHP:

$tmp = array_flip( $a );
asort( $tmp );
$a = array_flip( $tmp );

this gives me the array in PHP like this:

'14' => 'last',
'25' => 'second',
'33' => 'first'

so now a
in PHP will have the same order as a
for( i in ...)
in JavaScript. I was wondering if there is either a nicer way of sorting my array in PHP instead of flipping it twice -or- if there's an option for a loop in JavaScript that doesn't order the (admittedly confusing) integer value keys of my array?

Answer Source

All you need:



    14 => 'last',
    25 => 'second',
    33 => 'first',
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download