0

How can I put this array in foreach loop

Array (
    [title] => title0
    [des] => body0
    [0] => Array ( [title] => title1 [des] => body1 )
    [1] => Array ( [title] => title2 [des] => body2 )
    [2] => Array ( [title] => title3 [des] => body3 )
    [3] => Array ( [title] => title4 [des] => body4 )
    [4] => Array ( [title] => title5 [des] => body5 )
    [5] => Array ( [title] => title6 [des] => body6 )
    [6] => Array ( [title] => title7 [des] => body7 )
    [7] => Array ( [title] => title8 [des] => body8 )
    [8] => Array ( [title] => title9 [des] => body9 )
)

I tried

foreach($array as $a){
    echo $a->title;
}

but it didn't work out.

Error I got

ErrorException
Attempt to read property "title" on string 
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Tpp
  • 159
  • 7
  • Your array has varying depths. The first two elements `title` and `desc` are scalar while all other instances of `title` and `desc` are nested in rows. Looks like an XY problem where you have inappropriately built your array. `->` is for accessing object properties. You don't have an object and therefore, no properties. You have an array which in some cases contains arrays. Please always present your PHP array data on Stack Overflow from `var_export()`. You can find my conditional nested foreach advice on the dupe target. – mickmackusa Jan 18 '23 at 22:03
  • help me with the php code – Tpp Jan 18 '23 at 22:14
  • ...I did already. Help yourself to my free, pre-existing advice. – mickmackusa Jan 18 '23 at 22:17
  • your explanation is not understandable at all – Tpp Jan 18 '23 at 22:25
  • You know you have no solution you rush and close it, this is bad. – Tpp Jan 18 '23 at 22:38
  • I know that I have offered the correct solution. I have been generous in explaining the problem in my comment. I have even directed you to the exact answer on the duplicate page that will handle your data. There is no possible way that you are going to make me feel guilty about appropriately closing this page as a duplicate. If you are not a programmer or a programming enthusiast, then Stack Overflow is probably not the right place for -- you may wish to hire a programmer if you are unable to understand the very clear and basic advice being presented. – mickmackusa Jan 18 '23 at 22:43
  • This solved my problem ```foreach ($curated as $key => $value) { $gg = json_decode($value); print_r($gg->title); }``` – Tpp Jan 18 '23 at 22:54
  • Okay, that's great, but your question doesn't present any json strings at all. There is no way that anyone could have known that you had json data. – mickmackusa Jan 18 '23 at 22:55
  • I converted to json before decoding. @mickmackusa thanks anyway your explanation really helped – Tpp Jan 18 '23 at 22:57

0 Answers0