php associative array methods code example
Example 1: create a function that checks the values of the indexes in two arrays and keep a score
const triplets = (arr1,arr2) => {
let score1 = 0;
let score2 = 0;
let resultArr = [0,0]
for (let i = 0; i < arr1.length; i++){
if(arr1[i] === arr2[i]) {
resultArr[0] = score1
resultArr[1] = score2
} else if (arr1[i] > arr2[i]) {
score1++
resultArr[0] = score1
} else if (arr1[i] < arr2[i]) {
score2++
resultArr[1] = score2
}
}
return resultArr
}
Example 2: 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
}
]
}
}