PHP:array_splice()没有给我正确的输出

时间:2012-12-04 06:52:51

标签: php arrays multidimensional-array push array-splice

我正在尝试使用array_splice,我得到这样的输出(来自$ match)

Array
(
    [Keep me Updated] => Array
        (
            [winner] => winnerl.jpg
            [0] => value0.jpg
        )

    [0] => valuel.jpg //this should really be inside [Leep me Updated] array
    [1] => value2.jpg //this should really be inside [Leep me Updated] array
    [2] => value3.jpg //this should really be inside [Leep me Updated] array
}

from(此foreach创建将值放入$ match中)

foreach($data as $d)
{
    if (isset($match[$d['data']['name']])) {
        $match_loser = array($d['loser']['lrg_img']);

        array_splice($match,1,0,$match_loser);
    }else{
        $match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
                                            $d['loser']['lrg_img']);        
    }
}

我想要的是将[0],[1],[2]带入[Keep me Updated] $ match数组:

Array
(
    [Keep me Updated] => Array
        (
            [winner] => winnerl.jpg
            [0] => value0.jpg
            [1] => value1.jpg   // old one: [0] => valuel.jpg
            [2] => value2.jpg   // old one: [1] => value2.jpg
            [3] => value3.jpg   // old one: [2] => value3.jpg
        )
}

这就是$ data的样子

    $data[] = array(
    "data"=>array
    (
        "name"=>$name,
    ),
    "winner"=>array
    (
        "lrg_img"=>$img_url_winner
    ),      
    "loser"=>array
    (
        "lrg_img"=>$img_url_loser
    )

$ data有数组值,$ match是我试图对数据进行排序的地方。因此,如果我的值匹配,它就会合并。

谢谢!

1 个答案:

答案 0 :(得分:1)

使用内部数组作为array_splice

的参数
foreach($data as $d)
{
    if (isset($match[$d['data']['name']])) {
        $match_loser = array($d['loser']['lrg_img']);

        array_splice($match[$d['data']['name']],1,0,$match_loser);
    }else{
        $match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
                                            $d['loser']['lrg_img']);        
    }
}