1

I have an array with following elements: $arr = ['N','P','K','Ca','Mg','S', 'Zn', 'B','Cu','Fe','Mn','Mo'];

How can I use the array element as an object key in order to get only the values for the specific key:

object(stdClass)[727]
      public 'id' => int 1
      public 'name' => string 'John Doe' (length=8)
      public 'fname' => string 'HOUSE' (length=5)
      public 'bname' => string 'BLOCK 9' (length=7)
      public 'hectares' => float 7.2
      public 'cname' => string 'Vitis vinifera' (length=14)
      public 'delivery' => string '2210.0000' (length=9)
      public 'view_application' => int 1
      public 'view_schedule' => int 1
      public 'edit_schedule' => int 0
      public 'updated_at' => string '2020-07-17 20:03:51' (length=19)
      public 'N' => string '4.9000' (length=6)
      public 'P' => string '1.1000' (length=6)
      public 'K' => string '6.0000' (length=6)
      public 'Ca' => string '5.4000' (length=6)
      public 'Mg' => string '0.8000' (length=6)
      public 'S' => string '0.0000' (length=6)
      public 'Zn' => string '0.0210' (length=6)
      public 'B' => string '0.0071' (length=6)
      public 'Cu' => string '0.0280' (length=6)
      public 'Fe' => string '0.0420' (length=6)
      public 'Mn' => string '0.0220' (length=6)
      public 'Mo' => string '0.0000' (length=6)

I tried using this:

@for ($i = 0; $i < count($arr); $i++)
   $object->$arr[$i];
@endfor

But this gave an error Array to string conversion

The alternative is to convert the object to array using $newarr = (array) $object; Then iterating using $object[''.arr[$i].''];

But this won't work in my case as I have done most of my project using the object. Is there a way to use an array element as object key without converting the object to an array?

1 Answer 1

3

You need to make it recognise that the second part is the name of an element, so encapsulate it in braces...

$object->{$arr[$i]};
Sign up to request clarification or add additional context in comments.

2 Comments

Great! That's it. Thank you. Did you find a duplicate as I did not? If you don't find a duplicate within 24 hrs I will mark your answer as the solution. What does the curly braces do with the key? I know that is the mark of initialising an object.
I cannot wait any longer. Marked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.