1

I'm writing a php web application where I have a nested array which looks similar to the following:

$results = array(
        array(
            array(
                'ID' => 1,
                'Name' => 'Hi'
            )
        ),
        array(
            array(
                'ID' => 2,
                'Name' => 'Hello'
            )
        ),
        array(
            array(
                'ID' => 3,
                'Name' => 'Hey'
            )
        )
    );

Currently this means that when I want to use the ID field I have to call $results[0][0]['ID'] which is rather inefficient and with an array of over several hundred records becomes messy quickly. I would like to shrink the array down so that I can call $results[0]['ID'] instead.

My understanding is that a function that uses a foreach loop to iterate through each row in the array and change the format would be the best way to go about changing the format of the $results array but I am struggling to understand what to do after the foreach loop has each initial array.

Here is the code I have so far:

public function filterArray($results) {
    $outputArray = array();

    foreach ($results as $key => $row) {

    }

    return $outputArray;
}

Would anyone be able to suggest the most effective way to achieve what I am after?

Thanks :)

6
  • $outputArray[] = $row[0]; in foreach ? Commented Sep 11, 2015 at 9:10
  • Can you show the code who generated this array ? Commented Sep 11, 2015 at 9:11
  • @Fky I'm developing with CakePHP 2.7 and that was the way CakePHP returned the array from a SQL procedure. Commented Sep 11, 2015 at 9:14
  • 1
    im sure theres a way to modify the way your sql builds that result so that you dont have to deal with this. you should show us that code. Commented Sep 11, 2015 at 9:20
  • 1
    Maybe you can accept the answer of @Uchiha? Commented Sep 11, 2015 at 9:22

1 Answer 1

6

Simply use call_user_func_array as

$array = call_user_func_array('array_merge', $results);
print_r($array);

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Well Thanks @splash58

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.