Answers for "how to group array of objects by key in php"

PHP
1

group array php by key

private function group_by($array, $key) {
      $return = array();
      
      foreach($array as $val) {
          $return[$val->$key][] = $val; 
	  //  ou para gettype($val) = array
	  //  $return[$val[$key]][] = $val; 
      }
      return $return;
  }
Posted by: Guest on November-24-2020
1

php array group by key

$arrRoom[] = array("RoomCode" => "Deluxe",
                    "Rates" => array ( array(
                        "BoardCode" => "RO",
                        "Price" => 100)
                    ));
$arrRoom[] = array("RoomCode" => "Standard",
                    "Rates" => array ( array(
                        "BoardCode" => "RO",
                        "Price" => 100)                        
                    ));                    
$arrRoom[] = array("RoomCode" => "Deluxe",
                    "Rates" => array (array(
                        "BoardCode" => "RO",
                        "Price" => 200)
                    ));

foreach($arrRoom as $room)
{    
    foreach($room['Rates'] as $rates)
    {        
        $nRooms[$room['RoomCode']][$rates['BoardCode']][] = array("RoomCode" => $room['RoomCode'],
                                                            "MealCode" => $rates['BoardCode'],
                                                            "Price" => $rates['Price']);
    }
}
echo "\n ==== Output in Json Format ==== \n";
{
    "Deluxe": {
        "RO": [
            {
                "RoomCode": "Deluxe",
                "MealCode": "RO",
                "Price": 100
            },
            {
                "RoomCode": "Deluxe",
                "MealCode": "RO",
                "Price": 200
            }
        ]
    },
    "Standard": {
        "RO": [
            {
                "RoomCode": "Standard",
                "MealCode": "RO",
                "Price": 100
            }
        ]
    }
}
Posted by: Guest on May-26-2020

Code answers related to "how to group array of objects by key in php"

Browse Popular Code Answers by Language