从数据库结果中填充PHP数组

时间:2016-10-10 12:30:10

标签: php arrays

我需要构造一个这样的数组:

if(itemCount > capacity - 1){

好的,我有手动这个初始数组:

$data = array(
            array(1 => array("<span class=\"spanBig\">A</span> ROW GREENS", array(
                "A1" => "http://flexslider.woothemes.com/images/kitchen_adventurer_caramel.jpg",
                "A2" => "http://flexslider.woothemes.com/images/kitchen_adventurer_cheesecake_brownie.jpg",
                "A3" => "http://flexslider.woothemes.com/images/kitchen_adventurer_lemon.jpg"
            ))),
            array(2 => array("<span class=\"spanBig\">B</span> ROW BLUE",array(
                "B1" => "http://flexslider.woothemes.com/images/kitchen_adventurer_donut.jpg",
                "B2" => "http://flexslider.woothemes.com/images/kitchen_adventurer_caramel.jpg",
                "B3" => "http://flexslider.woothemes.com/images/kitchen_adventurer_cheesecake_brownie.jpg"
        ))));

这有更多元素,但现在这并不重要。相同的结构,但每个元素的最终数组都是空的。

我创建了一个for循环,它从每个类别中检索元素列表,将它们保存在一个数组中,最后将其保存在初始的空数组中,如下所示:

$data = array(
            array(3 => array("<span class=\"spanBig\">A</span> ROW GREENS", array())),
            array(4 => array("<span class=\"spanBig\">B</span> ROW LIGHTS", array())),
            array(5 => array("<span class=\"spanBig\">C</span> ROW GOLD/BROWN", array())),
            array(6 => array("<span class=\"spanBig\">D</span> ROW GOLD/BROWN", array())),
            array(7 => array("<span class=\"spanBig\">E</span> ROW DARK", array())),
            array(2 => array("<span class=\"spanBig\">F</span> ROW DEALS", array())),
            array(8 => array("<span class=\"spanBig\">M</span> ROW MARBLE", array())),
            array(1 => array("<span class=\"spanBig\">OF</span> ROW LEATHER", array()))//array() is the marker
        );

我再次拥有初始数组(不是所需的数组),为什么我不能将resultList保存在所需的位置?我知道da [1]来自for的本地数组。我正在尝试使用$ data进行一些组合,但我只打破了阵列。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

您是正确的$da是要分配给的数组的本地副本。要分配给原始数组,请在foreach循环中使用引用:

foreach($data as &$dat){
    foreach($dat as $key => &$da){

或者在两个 foreach循环中获取密钥,并使用密钥分配给原始数组:

foreach($data as $i => $dat) {
    foreach($dat as $key => $da) {
        // ...
        $data[$i][$key][1] = $resultList;