PHP/mySQL - how to fetch nested rows into multidimensinal array

后端 未结 2 1769
心在旅途
心在旅途 2020-12-10 20:22

Coming from another question of mine where I learnt not to EVER use db queries within loops I consequently have to learn how to fetch all the data in a convenient way before

2条回答
  •  清歌不尽
    2020-12-10 20:54

    It might be easier to first get all the scales, then all the items.

    //first get scales
    while ($row = fetchrowfunctionhere()) {
        $scale = $scales->createFromArray($row);
    }
    
    //then get items
    $lastId = null;
    while ($row = fetchrowfunctionhere()) {
        $scaleId = $row['scaleID'];
        if ($lastId != $scaleId) {
            $scale = $scales->getByScaleId($scaleId);
        }
        $item = $items->createFromArray($row);
        $scale->addItem($item);
        $lastId = $scaleId;
    }
    

    or everything in one sql

    $lastId = null;
    while ($row = fetchrowfunctionhere()) {
        $scaleData = array_slice($row, 0, 5, true);
        $itemData = array_slice($row, 5, 5, true);
        $scaleId = $scaleData['scaleID'];
        if ($lastId != $scaleId) {
            $scale = $scales->createFromArray($scaleData);
        }
        $item = $items->createFromArray($itemData);
        $scale->addItem($item);
        $lastId = $scaleId;
    }
    

    everything as one happy array

    while ($row = fetchrowfunctionhere()) {
        $scaleData = array_slice($row, 0, 5, true);
        $itemData = array_slice($row, 5, 5, true);
        $scaleId = $scaleData['scaleID'];
        if (!isset($scales[$scaleId])) {
            $scales[$scaleId] = $scaleData;
        }
        $itemId = $itemData['itemID'];
        $scales[$scaleId]['items'][$itemId] = $itemData;
    }
    

提交回复
热议问题