如何在PHP中附加到多维数组?

时间:2015-01-21 17:47:01

标签: php multidimensional-array arrays

所以,我正在使用以JSON格式发出信息的API,(基本上)以这种格式:

{"linkId":"1234asdf","clickData"
["member":{"userId":"asdf1234","email":"email@email.com","firstName":"Joe","lastName":"Schmoe"}]},
["member":{"userId":"fdsa4321","email":"liame@liame.com","firstName":"Moreo","lastName":"Hater"}],

- 针对电子邮件广告系列中的每个链接。我想通过嵌套的for循环&像这样组织它:

$linkCount = count($linkArray); //from previous API call

for ($i = 0; $i < $linkCount; $i++) {
    $clickReport[] = //API call here; omitted for brevity
    //parse the JSON here to get $linkid, $url; omitted for brevity
    $memberCount = substr_count($clickReport[$i],'"member":'); //to count number of people listed in JSON response
    for ($j = 0; $j < $memberCount; $j++) {
        //parse the JSON here to get $euid, $fname, $lname, $email; omitted for brevity
        $clickers[] = array (
            $euid[$i] => array (
                'fname' => $fname[$j],
                'lname' => $lname[$j],
                'email' => $email[$j],
                'links' => array (
                        'linkid' => $linkid[$i],
                        'url' => $url[i],
                ),
            ),
        );
    }
}

我遇到的问题是,如果一个成员点击多个链接,嵌套的for循环将覆盖之前的'links' => array()。我如何写这样links 添加,而不是覆盖

1 个答案:

答案 0 :(得分:1)

只需单独附加。

for ($j = 0; $j < $memberCount; $j++) {
    $clickers[] = array(
        $euid[$i] => array(
            'fname' => $fname[$j],
            'lname' => $lname[$j],
            'email' => $email[$j]
        )
    );
    $euid[$i]['links'][] = array (
        'linkid' => $linkid[$i],
        'url' => $url[i],
    );
}