minimal
minimal

Reputation: 31

Can you force PHP to view a numeric key as an associative array key?

Having an odd problem with an associative array. This code:

$sql = DB::select('id','process_id')->from('field')->order_by('process_id')->order_by('sort_order');
$query = $sql->execute();

foreach($query->as_array() as $row){
    $results[$row['id']] = $this->get_field($row['id']);
}      

creates an array with a numeric key. In my development environment the array is treated as an associative array and is ordered exactly as it's built from the query. However, in production it's treating the key as a number and sorting according to the ID. If I force PHP to consider the key associative by:

$results["a".$row['id']] = $this->get_field($row['id']);

it uses the MySQL sort. Unfortunately though there's a lot of code in place that depends on the key just being the ID.

Does anyone have any thoughts on why there might be a difference between servers? Any ideas for a workaround?

Upvotes: 3

Views: 1322

Answers (1)

Brendan Long
Brendan Long

Reputation: 54262

Maybe try casting it as a string?

$results[(string)$row['id']] = $this->get_field($row['id']);

Or if all you care about is order, just put them in as a normal list:

$results[] = $this->get_field($row['id']);

Upvotes: 2

Related Questions