I have a multidimensional array, that I need to sort after a given value (given from outside the array)
This is the array:
array (
[0] => array
(
["tfl_gpac_color"] => array([0] => "FF0000"),
["tfl_gpac_start"] => "1",
["tfl_gpac_end"] => "32"
),
[1] => array
(
["tfl_gpac_color"] => array([0] => "0000FF"),
["tfl_gpac_start"] => "33",
["tfl_gpac_end"] => "64"
),
[2] => array
(
["tfl_gpac_color"] => array([0] => "800080"),
["tfl_gpac_start"] => "65",
["tfl_gpac_end"] => "96"
)
)
I also have a given value from a config,
$strStartNumber = '33';
The strStartNumber changes, and I want the array sorted by this value in comparison with the 'tfl_gpac_start'.
If the number is 33,I want the first entry to be the one, with the 33 from 'tfl_gpac_start', if the value is 65, it should be starting with the 'tfl_gpac_start' with the number 65.
For '33' like this (compared to the one above):
array (
[0] => array
(
["tfl_gpac_color"] => array([0] => "0000FF"),
["tfl_gpac_start"] => "33",
["tfl_gpac_end"] => "64"
),
[1] => array
(
["tfl_gpac_color"] => array([0] => "800080"),
["tfl_gpac_start"] => "65",
["tfl_gpac_end"] => "96"
),
[2] => array
(
["tfl_gpac_color"] => array([0] => "FF0000"),
["tfl_gpac_start"] => "1",
["tfl_gpac_end"] => "32"
)
)
Thanks a lot for help, I tried several different ways, but I don't get it right...
EDIT: All values should be in the same place afterwards (should stay together), so the sort should only work on the key of the first array.
To rotate an array you might use this loop:
while ($array[0]['tfl_gpac_start'] !== $strStartNumber) {
$array[] = array_shift($array);
}
Note that these numeric values are strings - you need strict comparison
===
/!==
, because there are quirk cases with implicit string conversion that happens while comparing without type check. On the other hand if none value matches you'll get into infinite loop - i'd be careful with that either. You might add a couter to protect yourself:$count = count($array);
while(... && $count--) {
...
}
0 comments:
Post a Comment