简体   繁体   English

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

[英]How to parse PHP array with stdClass Object

Following is the array with stdClass Object 以下是带有stdClass对象的数组

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

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

What I want to get value of Content corresponding to Number 我希望获得与Number对应的Content

eg. 例如。 For Number 5 get value 00666 对于5获得值00666

Thank in advance. 预先感谢。

add this function: 添加此功能:

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
}

call the function something like this: 调用这样的函数:

echo returnContent($objArray, 5);

or assign it to a variable: 或将其分配给变量:

$content = returnContent($objArray, 5);

just be sure to check if the number existed: 请务必检查号码是否存在:

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

You can make a function for this: 你可以为此创建一个函数:

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

To use it use: 要使用它:

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

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

It will print `00666` and `1018456550591052212900797790669502`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM