I have aa function that returns an array that is structured like this
[[{"title":"Mr","first_name":"James","last_name":"Loo","date_of_birth":36356,"email":"test@test.com","phone_number":1234567890,"company":"CompanyOne"},{"title":"Mr","first_name":"Jonah","last_name":"Lee","date_of_birth":42629,"email":"test@test2.com","phone_number":1234567890,"company":"CompanyTwo"}],
[]]
Within the array are 2 arrays. The first one is a "entry not inserted" array and the second one is a "entry inserted" array.
However when I execute the code through this function
$result = $this->curl->execute();
$result_errors = array();
for($j=0;$j<sizeof($result);$j++){
$result_errors = $result[0];
}
if(sizeof($result_errors)>0){
echo json_encode($result_errors);
}
The result I get in the console is "[" only.
Am I missing something? I have read that I had to echo and json encode arrays but it doesn't seem to be coming out.
if $result
is literally as you've printed above, then it's not a PHP array, just a string in JSON format. PHP can't interpret it until you decode it. Your for
loop is a waste of time because you always assign the first index of $result
to your $result_errors
variable. In PHP if you try to fetch an index of a string, you simply get the character which is at that place in the string. The first character of $result
is "[".
If you're trying to get the first array out of that response, you need to decode the JSON into a PHP array, select the first inner array, and then re-encode that back to JSON for output, like this:
$array = json_decode($result);
echo json_encode($array[0]);
That will give you the first array, containing the two objects. If that's not the output you're after, then please clarify.
I am not sure you will get what you want but the problem is the assignment to $result_errors
. That var should be an array but when you make the assignment $result_errors = $result[0];
your change it from an array to whatever value is at $result[0]
; Try this
for($j=0;$j<sizeof($result);$j++){
$result_errors[] = $result[0];
}
My question to you is: Since $result is apparently an array (as indicated by the use of $result[0]
) then why not simply do this?
echo json_encode($result);
A suggestion: Instead of sizeof
use count
.
if(count($result_errors) > 0)
{
echo json_encode($result_errors);
}
count
is less likely to be misunderstood by others. It has a totally different meaning in other programming languages.
Oh, and the answer from @ADyson is right to point out the need to decode the json string into a PHP array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.