Skip to content
Advertisement

i am having difficulty with php foreach loop through array

i need help fetching values from an array,

Array ( [0] => stdClass Object ( 
[service] => text 
[reference] => 12345678 
[status] => approved 
[sender] => webmaster 
[mobile] => 123456789 
[message] => I need hekp. 
[data] => 
[price] => 3.2500 
[units] => 1 
[length] => 86c/1p 
[send_date] => 2021-05-20 15:42:41 
[date] => 2021-05-20 15:42:41 )  )

what i have done

$response = json_decode($result);
foreach($response as $value){
echo $value['units'];
}

i get an error 500 please kindly guide me i am lost

Advertisement

Answer

stdClass Object is telling us you have an object inside your array. so your $response structure looks like this in code:

[
    {
        "service": "text",
        "reference": 12345678
    }
]

try this:

$response = json_decode($result);
foreach($response as $value){
    echo $value->units;
}

in response yo your comment on this answer:

if you wanted to neaten this up you could replace the second reference to $response->data with $values:

$values = $response->data;
foreach($values as $value){
    echo "<table>
    <td>$value->reference</td>
    <td>$value->message</td>
    <td>$value->sender</td>
    <td>$value->mobile</td>
     <td>$value->status</td>
     <td>$value->units</td>
    </table>";
}

I suspect this is what you were going for when you wrote it out, but essentially you were declaring $values and then not using it…. then making a call to the same collection as $values.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement