当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Iterate through associative array and make new array using values

问题描述:

I am querying the values for my associative array and I need to change the way in which it looks and add values of '0' where values have not been returned (based on count of $result)

i.e. <=count($result) there are 4 rooms, but only rooms 1 & 3 are returned, but I still need r_id values 2 & 4 with a r_rate value of 0.

Currently my array looks like this:

Array

(

[0] => Array

(

[r_id] => 1

[r_rate] => 180.00

)

[1] => Array

(

[r_id] => 3

[r_rate] => 100.00

)

)

I want the array to look like this but I cannot define the arrays to merge as the r_id value will vary:

Array

(

[1] => 180.00 // [r_id] => [r_rate]

[2] => 0

[3] => 100.00

[4] => 0

)

I need the value of r_id to be the key, the value of r_rate to be the value, and to add the missing r_id values (2 & 4) with a value of 0.

SQL:

$sql = $dbh->prepare("SELECT booking_room.r_id, room.r_rate FROM booking_room, room

WHERE booking_room.b_id = '$b_id'

AND booking_room.r_id = room.r_id

");

$sql->execute();

$result = $sql->fetchAll(PDO::FETCH_ASSOC);

SQL Returns:

r_id | r_rate

1 | 180.00

3 | 100.00

I have tried so far:

foreach ($result as $v) {

foreach($v as $r) {

$r_id[] = $r;

}

}

$r_id = array_flip($r_id);

foreach ($r_id as $k => $v) {

$r_id[$k] = $k;

}

网友答案:

Something like this should do the trick.

This will loop through the $result array looking for numerical keys starting at 1, ending where ever you want, 4 in the example. If the key exists, we'll leave it alone, if it does not exist, we'll create it and set it to 0.

We'll run ksort at the end to sort the array items by the array key.

for ($r = 1; $r <= 4; $i++)
{
    if (!array_key_exists($r, $result))
    {
        $result[$r] = 0;
    }
}

ksort($result);
分享给朋友:
您可能感兴趣的文章:
随机阅读: