dongyun3897 2014-10-02 22:17
浏览 35
已采纳

通过关联数组迭代并使用值创建新数组

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;
}
  • 写回答

1条回答 默认 最新

  • drnf593779 2014-10-02 22:21
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: