mysql - Setting PHP Query into a nested array -
i trying use php logically store of data in nested associative arrays, , whenever loop through data or need reference data refer array pointer rather doing new queries each time.
for example:
my query is
$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 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 , cv.category_id = cat.id , cv.nominee_id = n.id left join users u on u.id = cv.user_id c.active = 1 order u.fullname, c.campaign_title, cat.category_order, cat.category_title, cn.nominee_order, n.title ") or die(mysqli_error());
and im trying set nested array like
$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']; }
so whenever point to:
$array[2][3]['category_title']
it print category title
do have ideas? literally been @ months , can't figure out.
use following:
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
associative array, don't need assign each element separately. need deal specially category information, has put nested associative array i've called categories
. access
$array[0]['categories'][1]['category_title']
you can loop on categories with:
foreach ($array[$campaign]['categories'] $cat) { echo "category id: {$cat['category_id']} title: {$cat['category_title']}<br>"; }
Comments
Post a Comment