Rahul Desai
Rahul Desai

Reputation: 15501

Append element to element of associative array

I am looking forward to developing an associative structure like this:

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

I tried to achieve this using array_push($opening_artist_stats[$artist_name], $value["fb_id"]); in the chunk of the code below, but it did not work.

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"]);

    }
}

Upvotes: 0

Views: 57

Answers (1)

Marcel
Marcel

Reputation: 5119

Just check, if the artist name key exists in your array. Otherwise set the key and put the ID in 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;
    }
}

Upvotes: 1

Related Questions