Search code examples
phpcodeignitermultidimensional-arrayarray-mergearray-push

push into every element of an multidimentional array


Sorry for being novice. i have a multidimensional array as under

array(3){
    [0] = array(2){
        [type]=>car,
        [model]=> mazda
    }
    [1]= array(2){
        [type]=>car,
        [model]=> lexus
    }
    [3]= array(2){
        [type]=>car,
        [model]=> lexus
    }
}

Now I want to loop through every type in this array and fetch result i.e. car company link from the database and want to push into this existing array. end result should look like

array(3){
    [0] = array(3){
        [type]=>car,
        [model]=> mazda,
        [link]=> http://mazda.com
    }
    [1]= array(3){
        [type]=>car,
        [model]=> lexus
        [link]=> http://lexus.com
    }
    [3]= array(3){
        [type]=>car,
        [model]=> rangerover
        [link]=> http://rangerover.com
    }
}

I can easily loop through this array and fetch result but I don’t know how to push this new result back into this array.

please help!!!


Solution

  • If you have the websites in the database, it might be the best idea to get all the data combined using a JOIN. Like this:

    (pseudo code)
    SELECT c.type,c.model,w.link 
    FROM cars AS c
    JOIN website AS w
    ON c.id = w.car_id
    

    If not, you must have some relation in your database to know for example that mazda is related to www.mazda.com (etc.). Then fetch all that data from the database, iterate through your array using the for loop and set something like this:

    for ($i=0; $i<count($origArray); $i++) {
        $origArray[i]['link'] = $dbArray['carName']; // or whatever the relation you have - name, id, etc...
    }
    

    Assuming that the $dbArray looks like this:

    'mazda' => 'http://mazda.com',
    'rangerover' => 'http://rangerover.com',
    etc...