【问题标题】:Loop through php array with stdClass Object使用 stdClass 对象循环遍历 php 数组
【发布时间】:2014-01-31 12:48:50
【问题描述】:

如何循环遍历这个数组并获取所有的 term_id?

Array (
    [0] => stdClass Object (
        [term_id] => 43
    )
    [1] => stdClass Object (
        [term_id] => 25
    )
)

【问题讨论】:

  • foreach ($arr as $item) { var_dump($item); }

标签: php arrays foreach stdclass


【解决方案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;
}

【讨论】:

    【解决方案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
    

    【讨论】:

    • 感谢您的快速回复,这是我写的,但我在选择的 html 元素中输出了我的代码,所以我找错地方了哈哈,将在 4 分钟内接受。
    猜你喜欢
    • 2014-06-18
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    相关资源
    最近更新 更多