数组到字符串类型转换

时间:2014-05-13 11:56:18

标签: php mysql arrays

我在将MYSQL关联数组传递到PHP数组时遇到问题 - 我收到错误消息:

  

数组到字符串类型转换

这是我的代码:

$sql="SELECT brand_id FROM brand
WHERE (name IS NOT NULL OR name != '')
  AND (name != 'Hot Brands')
ORDER BY name ASC";

$result=mysql_query($sql)or die(mysql_error());
while( $brand = mysql_fetch_assoc( $result)){
    $new_array[] = $brand; // Inside while loop
    }

    $arrlength=count($new_array);
    for($x=0;$x<$arrlength;$x++) {

?>

<?php

$sql1 = "SELECT COUNT(*) as total
    from shop_orders
        WHERE   
    DATE(CONCAT(shop_order_year,'-',shop_order_month,'-',shop_order_day))
        BETWEEN '2014-02-01' and '2014-05-01' AND brand = '".$new_array[$x]."'
        AND shop_order_action = 'Sale'";
} 
?>

这是数组

上print_r的结果
Array ( [brand_id] => 179 ) 
Array ( [brand_id] => 42 ) 
Array ( [brand_id] => 174 ) 
Array ( [brand_id] => 37 ) 
Array ( [brand_id] => 26 ) 
Array ( [brand_id] => 223 ) ... etc

有人可以解释为什么它没有将brand_id整数传递给SELECT COUNT(*)声明吗?

感谢。

2 个答案:

答案 0 :(得分:3)

您正在推送$new_array一个包含brand_id密钥和ID值的数组。您只想推送整数值,所以只需尝试:

while ($brand = mysql_fetch_assoc($result)) {
    $new_array[] = (int) $brand['brand_id'];
}

答案 1 :(得分:1)

您应该在while循环之前定义$ new_array数组,并将brand_id定义为关键如下:

$sql="SELECT brand_id FROM brand
WHERE (name IS NOT NULL OR name != '')
  AND (name != 'Hot Brands')
ORDER BY name ASC";

$new_array = array();

$result=mysql_query($sql)or die(mysql_error());
while( $brand = mysql_fetch_assoc( $result)){
    $new_array[] = $brand; // Inside while loop
    }

    $arrlength=count($new_array);
    for($x=0;$x<$arrlength;$x++) {

?>

<?php

$sql1 = "SELECT COUNT(*) as total
    from shop_orders
        WHERE   
    DATE(CONCAT(shop_order_year,'-',shop_order_month,'-',shop_order_day))
        BETWEEN '2014-02-01' and '2014-05-01' AND brand = '".$new_array[$x]['brand_id']."'
        AND shop_order_action = 'Sale'";
} 
?>

所以你不能使用

$new_array[$x]

但是

$new_array[$x]['brand_id']

当然,在这种简单的情况下,您也可以像上一个答案一样将array_id值添加到数组中。

您也不应该使用mysql函数,而是使用mysqli