Answers for "php group by array value"

PHP
1

php array group by value and get quantity

$array = array(
    array(
        "name"=>"Urus", 
        "type"=>"SUV", 
        "brand"=>"Lamborghini"
    ),
    array(
        "name"=>"Cayenne", 
        "type"=>"SUV", 
        "brand"=>"Porsche"
    ),
    array(
        "name"=>"Panamera", 
        "type"=>"Car", 
        "brand"=>"Porsche"
    ),
);

//filter by brand
$arrayFilterQty = array_count_values(array_column($array, "brand"));

/*
Array
(
    [Lamborghini] => 1
    [Porsche] => 2
)
*/
Posted by: Guest on September-24-2021
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

Browse Popular Code Answers by Language