简体   繁体   中英

How to fill multidimensional array with loop

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
        }
    }
}

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;
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM