0

I have an array :

$days = array(
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday'
);

And I have a query witch is getting me the days from the database (day_name,ID); For what I need your help: I want to fill the array with the loop below and make it associative. Example result :

thursday => array(
    'ID' => 1,
    'name' => thursday
),
friday => array(
    'ID' => 1,
    'name' => thursday
),
....eg

My code now:

$query='Query days from database';

foreach($query as $res)
{
    foreach($days as $day)
    {
        if($res == $day)
        {
            // now there I want to put informations
        }
    }
}
1
  • Hi and welcome to SO. Great to have you here. Please always format your code properly, so anybody can easily read it. Also consider using the search provided on the main page of SO! Commented Apr 15, 2021 at 19:21

2 Answers 2

2

There's no need for nested loops. Initialize the array as an associative array. Then use the name column from the database query to index into the result and assign to that element.

$days = ['sunday' => [], 'monday' => [], ...];
foreach ($query as $row) {
    $days[$row['name']] = $row;
}
Sign up to request clarification or add additional context in comments.

Comments

1

In case you can't initialize arrays (Like suggested in @Barmar Answer), you need to look for the array key to override it with an array. Like here :

$days=array('Sunday',
        'Monday',
        'Tuesday',
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday'
       );
    print_r($days);

//Example
$res[0]['name']="Sunday";
$res[0]['ID']="7";
$res[1]['name']="Monday";
$res[1]['ID']="1";

foreach($res as $k => $v){
$daykey = array_search($res[$k]['name'], $days);
if ($daykey !== false) {
    $days[$daykey]=array($res[$k]['name']=>array('ID'=>$res[$k]['ID'],'name'=>$res[$k]['name']));
} else {
    //do nothing... or whatever
}
} 
print_r($days);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.