Search code examples
phparraysjsonperformanceprocessing-efficiency

Accessing and filtering an array much more efficiently in php


I wrote a code to filter an json array and print some elements, but it caused a banishment for me for too much cpu usage (free hosting plan) can you help me make it more efficient? perhaps by using functions like array_filter here is my code:

$obj = json_decode($data,true);
$elements=count($obj)-1;
for ($x = 0; $x <= $elements; $x++){
  if ($obj[$x]["SymbolStateId"]==1)  {
  echo $obj[$x]["FirstOrderPage"]["ExchangeSymbols"]["NSCCode"];
  echo ",";
  echo $obj[$x]["FirstOrderPage"]["BestBuyPrice"];
  echo ";";

  }
}

Solution

  • Use array_walk + array_filter

    array_filter let you to filter the array elements and returns a new array with elements that satisfy the callback boolean statement.

    array_walk in the other hand lets you to iterate each array element and apply a callback function for each of that

    Please, use string concatenation operator to print more variables, don't make 3 statements for printing a string

    array_walk(
        array_filter(
            $array,
            function($item) {
                return $item["SymbolStateId"] == 1;
            }
        ),
        function($item) {
            echo $item["FirstOrderPage"]["ExchangeSymbols"]["NSCCode"] . "," . $item["FirstOrderPage"]["BestBuyPrice"] . ";";
        },
    );