使用stdClass对象循环访问php数组

问题描述 投票:0回答:2

如何遍历此数组并获取所有term_id?

Array (
    [0] => stdClass Object (
        [term_id] => 43
    )
    [1] => stdClass Object (
        [term_id] => 25
    )
)
php arrays foreach stdclass
2个回答
2
投票
$ob1 = new stdClass();
$ob1->term_id = 43;

$ob2 = new stdClass();
$ob2->term_id = 25;

$scope = array($ob1,$ob2);

foreach($scope as $o){
  echo $o->term_id.'<br/>';
}

// Out
// 43
// 25

1
投票

你的数组的每个元素都是一个常规对象,所以你可以通过for访问它(如果数组的元素是有序的,键是整数)或foreach(在示例中给$a数组):

对于:

$count = sizeof($a);
for ($i = $count; $i--;)
{
    echo $a[$i]->term_id;
}

的foreach:

foreach ($a as $item)
{
    echo $item->term_id;
}

如果要将所有ID添加到另一个数组,只需编写以下代码(在foreach的示例中):

$ids = array();
foreach ($a as $item)
{
    $ids[] = $item->term_id;
}
© www.soinside.com 2019 - 2024. All rights reserved.