如何使用stdClass对象解析PHP数组

时间:2014-02-01 14:03:08

标签: php arrays multidimensional-array

以下是带有stdClass对象的数组

Array
(
    [0] => stdClass Object
        (
            [Number] => 5
            [Content] => 00666
        )

    [1] => stdClass Object
        (
            [Number] => 7
            [Content] => 1018456550591052212900797790669502
        )
)

我希望获得与Content

对应的Number的价值

例如。对于数字5,获取值00666

提前感谢。

3 个答案:

答案 0 :(得分:2)

添加此功能:

function returnContent($myObjectArray, $number)
{
   foreach($myObjectArray as $obj){
      if ($obj->Number == $number)
         return $obj->Content;
      }
   }
   return "number not in array"; //or some other value to denote an error
}

调用这样的函数:

echo returnContent($objArray, 5);

或将其分配给变量:

$content = returnContent($objArray, 5);

请务必检查号码是否存在:

if ($content != "number not in array"){ //or whatever value you assigned to denote a failure
   //do something
}

答案 1 :(得分:1)

您可以为此创建一个功能:

function getContent($needle, $haystack) {
  foreach($haystack as $v) if($needle==$v->Number) return $v->Content;
  return null;
}

使用它:

$result = getContent(5, $myArray);
if($result===null) die('Value not found.');
// Use result however you want now

答案 2 :(得分:0)

$myObjectArray= myObjectArray() // array of objects

foreach($myObjectArray as $val) {
    echo $val->Content;
}

It will print `00666` and `1018456550591052212900797790669502`