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
     )
)

我怎样才能只得到对象[cat_id]=1

4

3 回答 3

1

尝试这个:

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

或者对于 PHP < 5.3:

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

$result然后应该包含您正在寻找的项目。

于 2013-05-29T15:49:42.993 回答
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])
}

完成后,$copy将只包含 cat_id 为 1 的对象。此方法将保留数组键。

于 2013-05-29T15:46:37.653 回答
0

$yourArray等于您问题中的数组。

$objects = array();

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

$objects然后将持有cat_id等于的项目1

或者,使用array_filter()功能:

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

$yourArray = array_filter($yourArray, "getCategory1Elements");
于 2013-05-29T15:42:44.090 回答