0

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;
}
2
  • What have you tried so far to rearrange your arrays using PHP? Please post your code. Commented Oct 2, 2014 at 22:19
  • I have tried a lot of things, array flipping was the closest I got, but basically does not give me the r_rate or missing keys :( So stuck! Commented Oct 2, 2014 at 22:23

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.