Reputation: 2599
I have array that need to sort by their appearance, as they are written manually as my free will. Note the values are hints to be expected to appear:
$options = array("the array retrieved from some forms");
$items = array();
foreach ($options as $key => $val) {
switch ($key) {
case 'three':
$items[] = "this should come first";
$items[] = "now the second in order";
$items[] = "the third";
$items[] = "forth";
switch ($val) {
case 'a':
case 'b':
$items[] = "fifth";
$items[] = "should be six in order";
break;
case 'c':
default:
$items[] = "7 in order";
break;
}
break;
...............
As you see the values can be anything, but what I need is to just implode and display the items based on their appearance. Its all manual order, what come first should be printed at top.
Expected:
"this should come first";
"now the second in order";
"the third";
"forth";
"fifth";
"should be six in order";
"7 in order";
Current unexpected:
"should be six in order";
"forth";
"7 in order";
"the third";
"fifth";
"this should come first";
"now the second in order";
But I can't seem to apply any of sorting from this http://www.php.net/manual/en/array.sorting.php I suspect those $items are ordered somewhere by the forms which I have no way to reorder. I just have power to write output and order as I want from top to bottom. But I can't inset keys into $items, simply because I need to reorder freely.
I took a look at the output, the keys are not sorted as expected.
Any hint is very much appreciated. Thanks
Upvotes: 0
Views: 97
Reputation: 57650
The way a php source appears to us is not same it is to compiler. So it's not possible that way. But it's possible (not in a good way) if you run a regex on the source.
Example:
$source = file_get_contents(__FILE__);
preg_match_all('#\$items\[\]\s*=\s*"([^"]+)"#', $source, $match);
// now $match[1] contains the strings.
$strings = $match[1];
Upvotes: 0
Reputation: 31
it seems the steps of fulfilling your array are not in order you want.
maybe you can use some trick to achieve what you want
for example insert "key pointer"
$ikey = 0;
$options = array("the array retrieved from some forms");
$items = array();
foreach ($options as $key => $val) {
switch ($key) {
case 'three':
$items[$ikey++] = "this should come first";
$items[$ikey++] = "now the second in order";
$items[$ikey++] = "the third";
$items[$ikey++] = "forth";
switch ($val) {
case 'a':
case 'b':
$items[$ikey++] = "fifth";
$items[$ikey++] = "should be six in order";
break;
case 'c':
default:
$items[$ikey++] = "7 in order";
break;
}
break;
i am not sure if this helps, because you posted uncomplete code.
sorry for my english, if there are any mistakes
Upvotes: 2