Appending objects to an array based on a field I am working with PHP5 (Laravel 5.1), and I couldn't optimize my function, which takes more 4 minutes turning, and fails in the end when I have a huge data (around 6500 rows, but working when i test with around 1000 rows only).
Basically, I try to get an array of objects (which contains users with their balances), and to append it to another array based on depositorId field (by creating a new array for the result).

protected function result(&amp;$items, $statements, $params, $order)
{
    $statements = iterator_to_array($statements);
    $accountTypeId = $this-&gt;getAccountTypeId($params);
    $allAccountTypes = $this-&gt;getAllAccountTypes($params, $accountTypeId);
    $balancesPerAccount = $this-&gt;getAllBalancesPerAccount($allAccountTypes, $order);
    $items = json_decode(json_encode($items), true);
    $appendedResult = [];

    foreach ($statements as $statement) {
       if (!$obj = array_search($statement-&gt;depositorId(), array_column($items,'id'))) continue;

       $obj = $items[$obj];

        $obj['className'] = User::class;
        $obj['gamepoints'] = $statement-&gt;balance();

        foreach ($allAccountTypes as $accountType) {
            $balancePerDepositor = array_search($obj['id'],
                array_map(function($object) {
                    return $object-&gt;depositorId();
                },
                    $balancesPerAccount[$accountType]
                )
            );
            $obj["gamepoints_".$accountType] = isset($balancePerDepositor) ? $balancesPerAccount[$accountTypeId][$balancePerDepositor]-&gt;balance(): "";
        }

        array_push($appendedResult,(object)$obj);
    }
}
If $statement contains a huge amount of data

I'm assuming the 6500 records are in the $statement iterator, and that the $statement iterator somehow will fetch data from a database.

Just removing the iterator_to_array statement in the first line can increase the speed a lot. If it's coming from a database query, it will first load ALL queries into memory, which you will read afterwards in your foreach loop.

Since you don't actually use the array for anything other than doing a foreach, this might speed up the results, because the data will only be fetched per-line in the foreach loop, rather than first fetching everything, and then looping over it.

Watch out with your array_* methods

You're using the array* methods heavily. While this is nice and short, I think you're missing some complexity going on in using the methods.

You're looking up all values in the array of $items for every item in $statements, while looking up all id's in the array of items.

This is a worst-case complexity of [Amount of statements]*[Amount of items]*2

Which you could easily reduce to a single associative array lookup.

Since $items is not changing inside the loop, you can safely make a single version of $items:

Here you're trying to lookup if the id exists in a property of statement:

if (!$obj = array_search($statement-&gt;depositorId(), array_column($items,'id')))


Keep in mind that key lookups in PHP are a lot faster than in_array or array_search lookups (they're the same in this case).

Basically in_array is this:

function in_array($array, $item)
    foreach ($array as $arrayItem)
    {
         if ($arrayItem == $array)
         {
              return true;
         }
    }
    return false;
 }


You could optimize this by first creating an associative array of all keys (once, outside the foreach loop):

foreach ($items as $subItem)
{
    $idIndex[$subItem] = $subItem;
}


You can also cache this information if you're calling this method multiple times.

And then checking inside your foreach loop:

if (!isset($idIndex[$statement-&gt;depositorId()])) {
    continue;
}


The cost of a lookup in $idIndex will alway be 1, and worst-case scenario of the lookup cost you're doing now will be 2n the amount of items in $items (e.g. ), because you will iterate $items twice each row.

Watch out with your array_* calls, part 2

Exactly the same principle applies to this part:

And here you're trying to look up if an id exists in $balancesPerAccount[$accountType]

$balancePerDepositor = array_search($obj['id'],
    array_map(function($object) {
        return $object-&gt;depositorId();
    },
    $balancesPerAccount[$accountType]
)


Since this a simple lookup, I would really recommend building an index of all balancedPerAccount once, and then checking with isset() if it exists, rather than looping over each item in a doubly nested array.

I would recommend doing an exercise of writing all array_* methods by hand using foreach or for loops, then it will become obvious what these methods are doing.

Unsolicited advise: Style, comments, variable names, reusing variable names

This will not affect speed that much, but I generally recommend overwriting variables with a different kind of Object. 
For example:

$items = json_decode(json_encode($items), true);


and

$obj = $items[$obj];


I would avoid this because


It's confusing to debug and test (obj used to be an int and now it's an object)
It becomes hard to read (what is actually the input and output of this method?)


PHP Doc
Also, depending on the objects, there's a lot of undocumented coding going on (documented by debugging). It's almost impossible to figure out what's happening without actually debugging the code. Make sure to use php annotations to describe what's inside the objects or arrays.

Variable naming


$items
$statement
$params
$order


Are all horribly generic in this case. If there are very clear comments on what they contain, this may not be a problem, but I would try using a bit more descriptive variable names.