从多维数组中获取值

时间:2013-01-23 23:31:43

标签: php arrays object

我收到了一个包含以下信息的对象

Array ( [0] => stdClass Object ( [campaigns_id] => 100 [views] => 28 )
        [1] => stdClass Object ( [campaigns_id] => 99 [views] => 346 )
        [2] => stdClass Object ( [campaigns_id] => 98 [views] => 73 )
        [3] => stdClass Object ( [campaigns_id] => 97 [views] => 204 )
        [4] => stdClass Object ( [campaigns_id] => 96 [views] => 10 )
        [5] => stdClass Object ( [campaigns_id] => 57 [views] => 12 )
      )

基本上,每行有两个值 - 一个ID和一个视图计数。

如果我的“广告系列ID”为“100”,我怎样才能成功从该对象中获取数字“28”?

3 个答案:

答案 0 :(得分:1)

尝试,

//$arr is the array, loop through it
foreach ($arr as $v) {
 if( $v->campaigns_id === 100 ) //Similarly you can get any other value for 'views'
  echo $v->views;
}

答案 1 :(得分:1)

循环播放数组

$yourval = 0;;

foreach( $yourarray as $id => $val ){

if( $val->campaigns_id === 100 ){
  $yourval = $val->views;
}

}

echo $yourval;

答案 2 :(得分:1)

你可以内联或作为一个函数执行此操作,我认为你可能更容易看到它是一个函数,所以在这里。

$view = get_view($the_array);

function get_view(& $my_array) {

  foreach($my_array as $object) {

    if($object->campaigns_id == 100) return $object->views;

  }

  return false;

}