phparraysmultidimensional-arraygroupingsub-array

Group multidimensional array data by a column value


$Show = [];
foreach ($result_radio as $Station => $Show) {
    $Show [] = array($result_radio[$Station]['StationID'] => $Show);
}

var_dump($Show) //outputs

array(19771) { // Number of Shows accross 182 Station
    [0] => array(1) {
        [24315] => array(16) {
            ["StationID"]=>"24315"
            ["Show"]=> "JaazOnline"
            ["Genre"]=> "Jazz"
            ...
    [1] => array(1) {
        [24315] => array(16) {
            ["StationID"] => "24315"
            ["Show"] => "Jaaz24/7"
            ["Genre"]=> "Jazz"
            ...
    [2] => array(1) {
        [24315] => array(16) {
            ["StationID"] => "24315"
            ["Show"] => "JazzUsa"
            ["Genre"] => "Jazz"
            ...
    [3] => array(1) {
        [66995] => array(16) {
            ["StationID"] => "66995"
            ["Show"] => "StateofTrance"
            ["Genre"] => "Electronic"
            ...
    [4] => array(1) {
        [66995] => array(16) {
            ["StationID"] => "66995"
            ["Show"] => "ElectroHouse"
            ["Genre"]=> "Electronic"
            ...

This returns an array of 19771 Radio Shows as arrays where $key is the StationID and Value $Show related information about this specific Show.

This is what I wanted, but I would like to format my array in a way instead to have only one array for each StationID and within all shows that belong to this ID.

for example e.g

array(182) {  // 182 Radio Stations
    [24315] =>  array(50) {  //Shows classified by Station Id
        array(16) { ["StationID"]=>"24315" ["Show"]=> "JaazOnline" ["Genre"]=> "Jazz" ...
        array(16) { ["StationID"]=>"24315" ["Show"]=> "Jaaz24/7" ["Genre"]=> "Jazz" ..
        array(16) { ["StationID"]=>"24315" ["Show"]=> "JazzUsa" ["Genre"]=> "Jazz" ...
    [66995]=>  array(32) { 
        array(16) {["StationID"]=>"66995" ["Show"]=> "StateofTrance" ["Genre"]=> "Electronic" 
        array(16) {["StationID"]=>"66995" ["Show"]=> "ElectroHouse" ["Genre"]=> "Electronic"

Why?
Because I think it makes my life easier client side to access objects properties this way.. Please any some help formatting this array of shows in a way to have ONE index representing a Station ID and within all shows...


Solution

  • What about this:

    $Show = array();
    foreach ($result_radio as $Station => $Show){
    $Show [$result_radio[$Station]['StationID']][] = $Show; } 
    

    It should do exactly what you want.