0
Array
(
[0] => stdClass Object
    (
        [product_id] => 12
        [cat_id] => 1
     )
[1] => stdClass Object
    (
        [product_id] => 23
        [cat_id] => 3
     )
[2] => stdClass Object
    (
        [product_id] => 44
        [cat_id] => 1
     )
)

How can I get only objects with [cat_id]=1 ?

brightintro
  • 1,016
  • 1
  • 11
  • 16
benedex82
  • 532
  • 2
  • 5
  • 18

3 Answers3

1

try this:

$result = array_filter($objects, function($a){ return ($a->cat_id === 1); });

or for PHP < 5.3:

function my_filter($a){ return ($a->cat_id === 1); }
$result = array_filter($objects, 'my_filter');

$result should then contain the items you are looking for.

StampyCode
  • 7,218
  • 3
  • 28
  • 44
  • I wonder what the performance difference is between using `array_filter` with a callback function as opposed to manually iterating the array with PHP's interpreted `foreach`. Would be interesting to see. – crush May 29 '13 at 15:50
  • built in functions are usually more efficient that loops, and `for(;;)` is usually more efficient that `foreach()` – StampyCode May 29 '13 at 15:52
  • Yes, but the built in `array_filter` still has to call an interpreted function. – crush May 29 '13 at 15:53
  • It's an anonymous function, not an interpreted one. It isn't compiled in userland, it's still precompiled, so shouldn't have significant drawbacks. – StampyCode May 29 '13 at 15:56
  • Your `my_filter()` function isn't compiled in userland? (even the anonymous form in 5.3+) That's news to me. – crush May 29 '13 at 15:57
  • http://stackoverflow.com/questions/8676888/anonymous-function-performance-in-php - actually that doesn't help. – StampyCode May 29 '13 at 15:59
  • Interesting read. thanks. – crush May 29 '13 at 16:01
0

Let $yourArray be equal to the array in your question.

$objects = array();

foreach ($yourArray as $entry) {
    if ($entry->cat_id === 1)
        $objects[] = $entry;
}

$objects would then hold the items with cat_id equal to 1.

Or, with array_filter() function:

function getCategory1Elements($value) {
    return $value->cat_id === 1;
}

$yourArray = array_filter($yourArray, "getCategory1Elements");
crush
  • 16,713
  • 9
  • 59
  • 100
0
$data = Array ( [0] => stdClass Object ( [product_id] => 12 [cat_id] => 1 ) [1] => stdClass Object ( [product_id] => 23 [cat_id] => 3 ) [2] => stdClass Object ( [product_id] => 44 [cat_id] => 1 ) );

$copy = $data;
foreach ($data as $key => $val) {
    if ($val->cat_id != 1) unset($copy[$key])
}

Once you're done, $copy will only contain object with a cat_id of 1. This method will preserve array keys.

Khior
  • 1,244
  • 1
  • 10
  • 20