简体   繁体   中英

php get array values

I have this array called inputs:

Array ( [0] => InputValidation Object ( [array:InputValidation:private] => Array ( [Id] => demo1 [Required] => [MinLength] => 10 [MaxLength] => [RegexName] => [RegexMsg] => ) ) [1] => InputValidation Object ( [array:InputValidation:private] => Array ( [Id] => demo2 [Required] => [MinLength] => 20 [MaxLength] => [RegexName] => [RegexMsg] => ) ) )

I must get value Id, Required, MinLength, MaxLength, RegexName and RegexMsg. I have tried to foreach like this

foreach ($this->inputs as $input){
            echo $input['Id'];
        }

But it give me an error: Cannot use object of type InputValidation as array

How can I do? Thanks

inputs is an array in which the first element (index 0) is an object.

But in your loop, you try to echo an object property as if the object was an array.

Try:

foreach ($this->inputs as $input){
  echo $input->Id;
}

Compared to JavaScript, objects in PHP cannot be accessed using the [] accessor, you have to use the -> accessor.

Yes I made a mistake. Array inputs has 1st index with an object InputValidation. This object also have a PRIVATE property named InputValidation (which is an associative array, where located the IdIindex you're looking for).

But this property is private. You won't be able to access it directly. You need a method on object InputValidation for that.

If that propery wasn't private but public, you woukd be able to access it as follow:

inputs [0]-> InputValidation-> InputValidation['Id'];

1st advice: avoid having an object which has a property with the same name than this object. That is confusing (I'd been trapped in it!)

2nd advice: read the doc about the objects you're using and PHP objects doc.

The advice from Comfreek looks like new feature in PHP or something that required well knowledge of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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