将元素追加到关联数组的元素

时间:2013-06-25 18:32:21

标签: php associative-array

我期待开发一个这样的关联结构:

Array(
'artist1' => Array('123','456','789')
'artist2' => Array('432', 543)
// and so on
)

我尝试在下面的代码块中使用array_push($opening_artist_stats[$artist_name], $value["fb_id"]);来实现此目的,但它不起作用。

foreach($session_info as $key=>$value){
    $artist_name = $value["s20"]["opening"]["artist"]["name"];
    $fb_id = $value["fb_id"];
    echo "<pre>ARTIST NAME: " . $value["s20"]["opening"]["artist"]["name"] . " FB ID " . $value["fb_id"] . "</pre>\n";
    array_push($opening_artist_stats[$artist_name], $value["fb_id"]);

    }
}

1 个答案:

答案 0 :(得分:1)

如果您的数组中存在艺术家姓名密钥,请检查。否则设置密钥并将ID放入int。

$opening_artist_stats = array();
foreach ($session_info as $key => $value) {
    $artist_name = $value["s20"]["opening"]["artist"]["name"];
    $fb_id = $value["fb_id"];

    if (isset($opening_artist_stats[$artist_name])) {
        $opening_artist_stats[$artist_name][]= $fb_id;
    } else {
        $opening_artist_stats[$artist_name] = array();
        $opening_artist_stats[$artist_name][] = $fb_id;
    }
}