2

With the help of variable categories i have this array in which all the arrays are without key/default index , because of this when i do $categories as $category in foreach and when i echo $category['name'] it gives illegal sting offet.

using laravel blade

enter image description here

What can be the possible solution for this or should i validate array first?

2
  • 1
    The categories might be objects. Try using $category->name instead. Commented Dec 12, 2017 at 5:56
  • NO they are not and i already tried this then the error is trying to get the property of non object. Commented Dec 12, 2017 at 6:20

2 Answers 2

3

The above code is in JSON format, convert to array first

for example

 $ex = {
         'result':"success",
         'categories':[{
              //your rest of the code
          }]
    }
    $data = json_decode($ex, TRUE);
//next use for each
     foreach($data as $key => $value)
     {
      //rest of your logic
     }
Sign up to request clarification or add additional context in comments.

1 Comment

"json_decode() expects parameter 1 to be string, array given"
1

I think this is your situation, and in my opinion, you are using the wrong variable to decode let me take your image as an example here.

    <?php

      $ex = [
     'result' => 'success',
       'categories' => [
      [
        'id'=>1,
        'name'=>'cat1',
    ],
    [
        'id'=>2, 
        'name'=>'cat21',
    ],
    [
        'id'=>3,
        'name'=>'cat31',
    ],
  ]
];
echo "<pre>";
$res = json_encode($ex);
print_r(json_decode($res));

in this example, I just showed you that I have done json_encode and json_decode easily without any issue and the output of JSON is same as your example image.

enter image description here

Thank You!

Comments

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.