Welcome Guest, Not a member yet? Register   Sign In
Adding Data to a MultiDimensional Array...
#2

In PHP you can use array keys to do a lot of work for you.

PHP Code:
// fetch list of cars
$cars $car_query->result_array();

// get all returned car IDs
$ids = [];
foreach (
$cars as $data) {
    
$ids[$data['ID']] = $data['ID'];
}

// user car IDs to get years, where getYearsArrayWithIDs is your query or other function
// you should return both ID and Year instead of just Year
$years getYearsArrayWithIDs($ids);

// make new array where key is Car ID and value is year
$idYears = [];
foreach (
$years as $data) {
   
$idYears[$data['ID']] = $data['Year'];
}

/*results 
[
    '123' => '2008',
    '654' => '2010',
    '789' => '2014'
]
*/

// loop over cars again and assign all years

foreach ($cars as $i => $data) {
    
// double check we have key/value in idYears before trying to access it
    
if (isset($idYears[$data['ID']])) {
        
$cars[$i]['Year'] = $idYears[$data['ID']];
    } else {
        
$cars[$i]['Year'] = false;
    }


Another option you can try, assuming the years come from DB too, is to join two tables when you do the original query.
Reply


Messages In This Thread
RE: Adding Data to a MultiDimensional Array... - by Pertti - 07-16-2018, 11:53 PM



Theme © iAndrew 2016 - Forum software by © MyBB