Reputation: 23
This is the array:
$response = array( 'message-count' => '1', 'messages' => array ( 0 => array ( 'to' => '12345667888', 'message-id' => 'XXXXXXXXXXX', 'status' => '0', 'remaining-balance' => '9.26820000', 'message-price' => '0.03330000', 'network' => '11111', ), ), );
What code do I use to get like, for example, the 'message-id' 's data?
I've tried $response->messages["message-id"]; but what I get is Trying to get property 'messages' of non-object Tried a lot of others as well they are all returning the same error
I am quite new to this so I hope I could get some help here
Sorry: Vardump gives me this, made a mistake with the code above
'{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}'
Upvotes: 1
Views: 115
Reputation: 106
$msg = '{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}';
$data = json_decode($msg);
$messageId = $data->messages[0]->{'message-id'};
var_dump($messageId);
If you have more than one message in the list then,
$messages = $data->messages;
foreach ($messages as $index => $message) {
var_dump($message); // whole message detail
var_dump($message->{'message-id'});// message-id
}
Upvotes: 0
Reputation: 2728
I would use array_column
function like this
array_column($response['messages'], 'message-id');
Upvotes: 0
Reputation: 1651
response is an array, you can't get messages
like -> , You should get message-id
by this way:
$jsonStr = '{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}';
$data = json_decode($jsonStr);
$messageId = $data->messages[0]->{'message-id'};
echo $messageId; //or var_dump($messageId)
Upvotes: 2
Reputation: 6751
Your array contains non-object values so you can retrieve the values as below.
<?php
$response = array('message-count' => '1', 'messages' => array(0 => array('to' => '12345667888', 'message-id' => 'XXXXXXXXXXX', 'status' => '0', 'remaining-balance' => '9.26820000', 'message-price' => '0.03330000', 'network' => '11111',),),);
echo $response['messages'][0]['message-id'];
// Output
// XXXXXXXXXXX
Upvotes: 1