将PHP Query设置为嵌套数组

时间:2015-04-01 16:24:53

标签: php mysql sql

我正在尝试使用PHP在嵌套的关联数组中逻辑存储所有数据,然后每当我循环数据或需要引用数据时,我都会引用数组指针,而不是每次都执行新的查询

例如:

我的查询是

$query = $db->query("
SELECT
    c.id campaign_id,
    c.campaign_title,
    c.start_date campaign_start_date,
    c.end_date campaign_end_date,
    cat.id category_id,
    cat.category_title,
    n.id nominee_id,
    n.title nominee_title,
    u.id voter_id,
    u.fullname voter_name
FROM
    campaign c
LEFT JOIN categories cat ON cat.campaign_id = c.id
LEFT JOIN category_nominees cn ON cn.category_id = cat.id
LEFT JOIN nominees n ON n.id = cn.nominee_id
LEFT JOIN category_votes cv ON cv.campaign_id = c.id
AND cv.category_id = cat.id
AND cv.nominee_id = n.id
LEFT JOIN users u on u.id = cv.user_id
WHERE
    c.active = 1
ORDER BY
    u.fullname,
    c.campaign_title,
    cat.category_order,
    cat.category_title,
    cn.nominee_order,
    n.title
") or die(mysqli_error());

我试图设置嵌套数组,如

$array = array() ;

while($row = mysqli_fetch_assoc($query)) {

  $array[$row['campaign_id']] = $row['campaign_id'];
  $array[$row['campaign_id']]['campaign_title'] = $row['campaign_title'];
  $array[$row['campaign_id']]['campaign_start_date'] = $row['campaign_start_date'];
  $array[$row['campaign_id']]['campaign_end_date'] = $row['campaign_end_date'];
  $array[$row['campaign_id']]['campaign_title'] = $row['campaign_title'];
  $array[$row['campaign_id']]['category_id'] = $row['category_id'];
  $array[$row['campaign_id']]['category_id']['category_title'] = $row['category_title'];
}

每当我指出:

$array[2][3]['category_title']

会打印类别标题

你有什么想法吗?我真的已经好几个月了,无法弄清楚。

1 个答案:

答案 0 :(得分:1)

使用以下内容:

while ($row = mysqli_fetch_assoc($query)) {
    if (!isset($row['campaign_id'])) {
        $array[$row['campaign_id']] = $row;
    }
    if (!isset($array[$row['campaign_id']]['categories'])) {
        $array[$row['campaign_id']]['categories'] = array();
    } 
    $array[$row['campaign_id']]['categories'][$row['category_id']] = array('category_id' => $row['category_id'], 'category_title' => $row['category_title']);
    }
}

$row已经是一个关联数组,您不需要单独分配每个元素。您只需要特别处理类别信息,该类别信息必须放入我称为categories的嵌套关联数组中。所以你可以访问它

$array[0]['categories'][1]['category_title']

您可以使用以下内容循环遍历所有类别:

foreach ($array[$campaign]['categories'] as $cat) {
    echo "Category ID: {$cat['category_id']} Title: {$cat['category_title']}<br>";
}