Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've got an array that looks like this:

Array
(
    [0] => Array
        (
        [id] => abc
        [name] => Charlotte
        [state] => NC
        )
    [1] => Array
        (
        [id] => def
        [name] => Tampa
        [state] => FL
        )
)

What I am trying to do is pull two of the values from each nested array ('id' and 'name'), run a function on them, and return an array that is then nested. So, for each 'id' and 'name,' pass that to "function work($id,$name)," which returns an array, such that the resulting array looks like this:

Array
(
    [0] => Array
        (
        [id] => abc
        [name] => Charlotte
        [state] => NC
        [restaurants] => Array (
                               [rname] => Good Burger
                               [rname] => McD
                               )
        )
    [1] => Array
        (
        [id] => def
        [name] => Tampa
        [state] => FL
        [restaurants] => Array (
                               [rname] => BK
                               [rname] => White Castle
                               )
        )
)

My searches on here found a few ways of pulling the values from the original arrays (foreach() loop), but I am unsure of the best way to pass these values to a function (array_walk doesn't appear to be an option in this case?), and especially of how to return a nested array into another nested array.

Am glad to provide clarification is need be.

share|improve this question

2 Answers

up vote 1 down vote accepted
foreach ($array as $key => $value){
   $array[$key]['restaurants'] = work($value['id'],$value['name']);
}

function work($id,$name){
    $results = array();
    ///process data
    return $results;
}
share|improve this answer

Try something like this:

foreach($cities as &$city){
    $city['restaurants'] = work($city['id'],$city['name']);
}

Demo with a dummy function.

The &$city tells PHP that you want to be able to modify the record in your loop (passes the array by reference instead of as a copy).

After this, you can simply set the restaurants value to the array returned by the work function.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.