I am working on a php project and I need some help with an array problem.
The array, as it sits, is a non-associative array of objects. These objects each have a field called $_prompt, which contain strings that start with a number.
Example: “42. What you want to do is…”
Now, I can convert it to an assoc array using split and such so that $items[42] = <original object> but the order is still messed up. I’ve tried just about all combinations of ksort, krsort, sort, asort, and so on, and just cannot get things to be in order in a foreach.
Ok assume the following (I have no control over the delivery of this).
// this is what I use to deserialize things...
class Question
{
public $_prompt;
public $_choices;
}
// so what I get is a non assoc array of Question instances.
$instances = array();
$instances[] = $q1;
// through
$instances[] = $q50;
// when I loop, they are out of order
foreach ($instances as $instance) // not in expected order...
// so I tried this...
$items = array();
foreach ($questions as $question)
{
// grab the numeric key from the prompt
$key = array_shift(explode(".", $question->_prompt));
$items[$key] = $question;
}
ksort($items, SORT_NUMERIC);
return $items;
// when I loop, they are out of order
foreach ($items as $item) // STILL not in expected order...
Originally, they were added in order and serialized, the reverse of this. On de-serialization, they are no longer in order. The prompt contains the “entire” question, except for the choices. An exmple prompt may be “1. The is your first question”, and no, I cannot change that.