Julian S Julian S - 2 months ago 6
PHP Question

Preferred approach for creating a new array based on mysql results

I want to create a new array which stores order_status as the key, and count as the value. Now I have two approaches.

Which approach is the preferred one?

Approach #1

$ordersStatus = array();
$count = array();
while ($row = my_db_fetch_array($sql)) {
$ordersStatus[] = $row['orders_status'];
$count[] = $row['count'];
}
$orders_status_count = array_combine($ordersStatus, $count);


Approach #2

while ($row = my_db_fetch_array($sql)) {
$orders_status_count[$row['orders_status']] = $row['count'];
}

Answer

The second approach is preferable because maintaining the key => value integrity preserves the original association of the data, which you would eventually need to get back anyway if you used 2 separate arrays as in the first approach!

Also, the loop should be:

while ($row = my_db_fetch_array($sql)) {
    $orders_status_count[$row['orders_status']] = $row['count'];
}
Comments