skip to Main Content

I was trying to print array inside a foreach loop in following way:

@foreach($response['results'] as $row)
    <tr>
       <td>
         @foreach($row['status'] as $r)
            Status-  {{$r['groupName']}}   //  it shows above error on this line
         @endforeach
       </td>
       <td>{{$row['from'] - $row['sentAt']}}</td>
       <td>{{$row['to'] - $row['doneAt']}}</td>
    </tr>
@endforeach

I have checked in every response and I have got status value on each response. Here is my array response:

"results" => array:14 [▼
      0 => array:13 [▼
        "messageSegments" => array:3 [▶]
        "sentAt" => "2024-02-23T04:41:01.881Z"
        "doneAt" => "2024-02-23T04:41:03.267Z"
        "mmsCount" => 3
        "mccMnc" => "310260"
        "price" => array:2 [▶]
        "status" => array:5 [▼
          "groupId" => 3
          "groupName" => "DELIVERED"
          "id" => 5
          "name" => "DELIVERED_TO_HANDSET"
          "description" => "Message delivered to handset"
        ]
        "error" => array:5 [▼
          "groupId" => 0
          "groupName" => "OK"
          "id" => 0
          "name" => "NO_ERROR"
          "description" => "No Error"
        ]
        "applicationId" => "default"
      ]
      1 => array:13 [▶]
      2 => array:14 [▶]
      3 => array:14 [▶]

But it shows following error :

Trying to access array offset on value of type int

What could be possible error behind that and how to solve it?

2

Answers


  1. You should review the basics about arrays, you don’t have to loop over your index since it’s just a multidimensional array. You can access what directly by:

    $row['status']['groupName']
    
    Login or Signup to reply.
  2. While you loop your status array, your first element is the groupId with the value of 3, an integer. When you try to do $r['groupName'] where $r is an integer, you will end up having the issue you mentioned in the question. Instead:

    @foreach($response['results'] as $row)
        <tr>
           <td>
                Status-  {{$row['status']['groupName']}}   //  it shows above error on this line
           </td>
           <td>{{$row['from'] - $row['sentAt']}}</td>
           <td>{{$row['to'] - $row['doneAt']}}</td>
        </tr>
    @endforeach
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search