Jump to content

Strange behaviour of print_r with a milti-dim array


Mardoxx

Recommended Posts

<?php
echo_all($grouped_array);

function echo_all($array) {
echo nl2br(str_replace(' ',' ',print_r($array,true)));
}

 

gives the output...

[truncated by me]

Array
(
    [0] => Array
        (
            [0] => 131
            [2] => 137
            [4] => January ||| February ||| March
            [5] => 4.294091292µs ||| 9µs ||| 4.5µs
            [1] => 194
            [3] => 202
        )

    [1] => Array
        (
            [0] => 163
            [2] => 169
            [4] => January ||| February ||| March
            [5] => 9.632959861µs ||| 16µs ||| 8µs
            [1] => 192
            [3] => 201
        )

 

It gives the array in the way I entered the data...

How come it's not in the order of 0 to 5?

Is there any way I can resort it?

The indexes are in the order in which they were created. You could either create each sub-array in the order you want or sort it by the keys at the time you add it to the main-array or you could iterate through the main-array and replace each sub-array with a sorted version of itself.

 

Edit: And does it really matter, you will access each element by its' key value anyway?

<?php
function key_sort($multiarray) {	
	foreach ($multiarray as $group_index => $group) {
		ksort($array[$group_index]);		
	}
}	

 

<?php
function key_sort($multiarray) {	
	foreach ($multiarray as $group_index => $group) {
		ksort($group);	
//print stuff here or w/e	
	}
}	

 

not sure what the difference is I think the first one, $group is already set.. so doesn't get sorted

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.