php - Array - Add value depending on other value

I would like to add values to an array, depending on other values alrdy in the array.
My script:
$today = date("Ymd");
$finalDate = date('Ymd', strtotime('+2 days'));
foreach ($arr as $key => $value) {
if ($value['DTSTART'] <= $finalDate){
$values[] = array(
'day' => $value['DTSTART'],
'type' => $value['SUMMARY;LANGUAGE=en']
);
}
}
Type is something like this: Non-recyclable waste, Bio-waste, etc.
I want to add colors to the array depending on the waste type. I tried it like this, but it adds another 'sub-array'.
foreach ($arr as $key => $value) {
if ($value['DTSTART'] <= $finalDate){
$values[] = array(
'day' => $value['DTSTART'],
'type' => $value['SUMMARY;LANGUAGE=en']
);
switch ($value['SUMMARY;LANGUAGE=en']) {
case "Non-recyclable waste":
$values[] = array(
'color' => 'success'
);
break;
case "Bio-waste":
$values[] = array(
'color' => 'success'
);
break;
}
}
}
// Edit: The Input array:
Array ( [0] => Array ( [DTSTART] => 20210712 [DTEND] => 20210713 [TRANSP] => TRANSPARENT [LOCATION;LANGUAGE=en] => streetname [UID] => uid [DTSTAMP] => 20210707T015623Z [DESCRIPTION;LANGUAGE=en] => description [SUMMARY;LANGUAGE=de] => Bio-waste [PRIORITY] => 9 [CLASS] => PUBLIC [STATUS] => CONFIRMED ) [1] => Array ( [DTSTART] => 20210726 [DTEND] => 20210727 [TRANSP] => TRANSPARENT [LOCATION;LANGUAGE=en] => street [UID] => uid [DTSTAMP] => 20210707T015623Z [DESCRIPTION;LANGUAGE=en] => description [SUMMARY;LANGUAGE=en] => Non-recyclable waste [PRIORITY] => 9 [CLASS] => PUBLIC [STATUS] => CONFIRMED )
Answer
Solution:
Create an item array with unconditional data (day and type). Add conditional data (color) as needed. Push the array to the main array.
$values = [];
foreach ($arr as $key => $value)
{
if ($value['DTSTART'] <= $finalDate)
{
$item = array(
'day' => $value['DTSTART'],
'type' => $value['SUMMARY;LANGUAGE=en'],
);
switch ($value['SUMMARY;LANGUAGE=en'])
{
case "Non-recyclable waste":
case "Bio-waste":
$item['color'] = 'success';
break;
// Add more cases.
}
$values[] = $item;
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: your lock file does not contain a compatible set of packages. please run composer update
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.