从嵌套数组中检索结果

时间:2014-09-20 17:15:09

标签: php arrays foreach

我无法理解如何将结果拉出来。我继续使用那些echo语句获得“Array”,“Array”。感谢

$qry  = "SELECT * FROM `users` WHERE installation_id = $installation_id";
$res = mysqli_query($mysqli, $qry) or die('-1'.mysqli_error($mysqli));

$categories = array();
while ($row_rsCategories = mysqli_fetch_assoc($res)) { 
    $product_array = array();
    $product_array_query = mysqli_query($mysqli,"SELECT id, user_id, client_id, comments, stars FROM reviews WHERE user_id = '".$row_rsCategories['userId']."'");

    while($product_array_fetch = mysqli_fetch_array($product_array_query)) {
       $product_array[] = array(
           "id" => $product_array_fetch['user_id'],
           "name" => $product_array_fetch['comments']
       );
    }                

    $categories[] = array(
        'id' => $row_rsCategories['userId'],
        'name' => $row_rsCategories['userName'],
        'products' => $product_array,
    );
}

foreach ($categories as $category) {
    echo $category['name'];
    echo $category['products'];
}

更新:

我在调用usersName时发现一个错误。所以现在它将两个用户名一起打印出来。

Catergory数组是:

Array
(
    [id] => 63
    [name] => Paul Rothlisberger
    [products] => Array
        (
        )
)

1 个答案:

答案 0 :(得分:0)

"数组"打印,因为这是数组$category['products']的字符串表示形式。要以逗号分隔列表打印每个产品的所有信息,请使用:

foreach($category['products'] as $product) {
    echo implode(",", $product);
}

换句话说,您必须将数组中的每个元素迭代到最里面数组中的单个值。

更新:错过了您的产品也是数组的事实。更新了解决方案。