John Davidson

arrays - How Do I retrieve a string value JSON in PHP?

0 comments
Message:


I have a returned string result from an API and it looks like this.. for the life of me, I cannot retried the WorkID value!


The returned string is a json string:


{"notes":"","RecordsStatus":"{\"0\":{\"WorkID\":\"0090210\",\"Message\":\"Record Created\"}}"}

It has two parts:
“notes” and “RecordStatus”.
If message is empty, means the batch is imported without error.
In RecordStatus, there are two parts too.
First is the index number of the record, and it has second part that the key for the record created(in my case it’s the WorkID) and a message tells the record is created or updated(in my case, it’s created).


Array
(
[notes] =>
[RecordsStatus] => {"0":{"WorkID":"0090210","Message":"Record Created"}}
)

Do a Var_dump() of decoded_json results in this:


array(2) {
["notes"]=>
string(0) ""
["RecordsStatus"]=>
string(52) "{"0":{"WorkID":"0090210","Message":"Record Created"}}"
}

I tried


foreach($decoded_json as $item) { 
$uses = $item['RecordsStatus'][0]['WorkID']; //etc
}

but does not work



My Answer:
To retrieve the WorkID value from the JSON string in PHP, you need to first decode the JSON string using the `json_decode` function. Then, you can access the WorkID value by traversing the decoded array.

Here is an example code snippet to retrieve the WorkID value:

php
// Your JSON string
$jsonString = '{"notes":"","RecordsStatus":"{\"0\":{\"WorkID\":\"0090210\",\"Message\":\"Record Created\"}}"}';

// Decode the JSON string
$decoded_json = json_decode($jsonString, true);

// Access the WorkID value
if(isset($decoded_json['RecordsStatus']['0']['WorkID'])) {
$workID = $decoded_json['RecordsStatus']['0']['WorkID'];
echo $workID; // Output: 0090210
} else {
echo "WorkID not found";
}


In this code snippet, we first decode the JSON string using `json_decode` with the second parameter set to `true` to decode the JSON string into an associative array. Then, we access the WorkID value by traversing the decoded array using the keys 'RecordsStatus', '0', and 'WorkID'. If the WorkID value is found, we store it in the `$workID` variable and output it.

Rate this post

3 of 5 based on 5108 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us