Answers for "array group by value php"

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
0

php group array by value and count

$colors=array("red","red","red","blue","green");
$colorsCount=array_count_values($colors);
print_r($colorsCount);
#Array
#(
#    [red] => 3
#    [blue] => 1
#    [green] => 1
#)
Posted by: Guest on December-05-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