php - 如何从单个查询中获取数组中的值

标签 php mysql

我有一个

Book ID Array

    Array
    (
        [0] => 61
        [1] => 72
        [2] => 78
        [3] => 100
        [4] => 102
    )

现在从另一个表 table_bookPrice 中给出价格归档 我希望从 table_bookPrice 中选择所有价格,其中书籍 ID 在给定数组(书籍 ID 数组)中,如果 table_bookPrice 字段中未提及价格,那么它将自动为 500

什么是精确查询

所以我得到的数组是这样的

Book Price Array

    Array
    (
        [0] => 150
        [1] => 100
        [2] => 500 ( not mentioned in table, so it is 500)
        [3] => 300
        [4] => 200
    )

最佳答案

我在工作所以无法测试或编译它,但我希望我的逻辑是可以理解的。

不确定这是否行得通,但按照这些思路行事

$book_price_array = array(); //contents to be added.

// loop through the array an examine its price by querying your table.
foreach ($book_id_array as $key => $value) {
   $price = mysql_query("SELECT price FROM table_bookPrice 
                                     WHERE book_id = {$value}");
   // there is a price, set the price.
   if ($price > 0 && $price != NULL)  $book_price_array[$key] = $price;

   // there is no price, set the default price
   else  $book_price_array[$key] = 500; 
}

关于php - 如何从单个查询中获取数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2155843/

相关文章:

php - 使用 LAST_INSERT_ID() 和来自另一个表的行在 PHP/MySQL 中进行两次插入

mysql - 安装mysql2时出错

java - 我使用了cursor_loop : loop in sql stored procedure its not fetching all 15 rows it fetch one row only

php - 按主题线程化电子邮件

php - 使用 Composer 安装/更新后是否应该自动从磁盘中删除依赖项?

php - 使用 PHP 连接到 MySQL(WAMP) 数据库

php - 与 php SELECT 作斗争

php - 如何将行回显到我的 html 中?

php - Mysql中如何防止负数

mysql - 将多行中的列值插入到单行中