在php中的where子句中使用数组

时间:2015-10-29 06:16:17

标签: php arrays

我有一个数组$order_mealsInfo_ids,其值如此

[{"meal_id":"33"},{"meal_id":"34"}]

meal_id&#34; 33&#34;和&#34; 34&#34;具有相同的值(store_name,franchise_id,order_datetime)所以我只想获得这些值,这就是我使用distinct keyword的原因。我想在我的查询中使用$order_mealsInfo_ids,我的查询是:< / p>

    $get_franchise_info="Select distinct store_name,franchise_id,order_datetime from order_main where id 
IN (".implode(',',$order_mealsInfo_ids['meal_id']).")";

但它给出了这个错误:

  

注意:未定义的索引:第94行的C:\ xampp \ htdocs \ learning \ service \ get_pending_orders_news.php中的meal_id

     

警告:implode():在第94行的C:\ xampp \ htdocs \ learning \ service \ get_pending_orders_news.php中传递的参数无效

3 个答案:

答案 0 :(得分:2)

在您的情况下,$order_mealsInfo_ids不是PHP数组。它是一个包含JSON数组的字符串。

请试试这个:

$order_mealsInfoJSON = '[{"meal_id":"33"},{"meal_id":"34"}]';
$order_mealsInfoArr = json_decode($order_mealsInfoJSON); // Convert JSON string to PHP array containing objects.

$order_mealsInfoIds = array();
foreach($order_mealsInfoArr as $order_mealsInfo) {
    $order_mealsInfoIds[] = $order_mealsInfo->meal_id;
}

$get_franchise_info="Select distinct store_name,franchise_id,order_datetime from order_main where id IN (".implode(',', $order_mealsInfoIds).")";

答案 1 :(得分:1)

<强> [{&#34; meal_id&#34;:&#34; 33&#34;},{&#34; meal_id&#34;:&#34; 34&#34;}] 这不是数组这是 json

您需要将 json转换为数组

`$array = json_decode($json);
$mapedarray = array_map('current',$array);
$data = implode(',',$mapedarray);
echo $data;
`

所以你得到33,34

`
 $get_franchise_info="Select distinct store_name,franchise_id,order_datetime from order_main where id 
IN (".implode(',',$mapedarray).")";
`

 `
     $get_franchise_info="Select distinct store_name,franchise_id,order_datetime from order_main where id 
    IN (".$data.")";
    `

答案 2 :(得分:0)

使用此

    $data_jsn = '[{"meal_id":"33"},{"meal_id":"34"}]';
    $data = json_decode($data_jsn,true);
    $data_val = array_map(function($element) {
      return $element['meal_id'];
    }, $data);

    $get_franchise_info="Select distinct store_name,franchise_id,order_datetime from order_main where id 
    IN (".implode(',',$data_val).")";