Decoding json in array , editing array and encoding in json - PHP - php

I am newbee in php and trying to get json in array and wanna change key in that json below is my code :
$json = json_decode(file_get_contents('all_json_files/jobs.json'), true);
foreach ($json as $key=>$row){
foreach ( $row as $key=>$row){
foreach ( $row as $key=>$row){
foreach ($row as $key=>$row){
if(strcmp($key,"security_block")==0)
{
foreach ($row as $k=>$r){
if(strcmp($k,"job_payload_hash")==0)
{
$row[$k]['job_payload_hash']=$base64String;
print_r($row);
}
}
}
}
}
}
}
print_r($json);
Issue is print_r($row); is updating properly but print_r($json); does not print the updated string .

If the key could appear anywhere, the answer is pretty simple:
function update_hash(&$item, $key, $base64String)
{
if ($key == "job_payload_hash") {
$item = $base64String;
}
}
array_walk_recursive($json, 'update_hash', 'something');
Update
The structure is something different that previously assumed; while the above will work, probably the below is a more direct approach:
foreach (array_keys($json['jobs']) as $jobId) {
$json['jobs'][$jobId]['job']['security_block']['job_payload_hash'] = 'something';
}

You use $key & $row variable in multiple time. for this reason, value of $key is changed each time, so parent loop does not work..
You can use recursive function lik answer of #Ja͢ck .

this is because you have to save not in variables you defined after => in a foreach.
You have to store this in format:
$json[0][0] ... = $base64String;
OR
You have to add a new array like $result = array() before you write the foreach and then store it in $result.

Decode the JSON string using json_decode(), edit your resulting array, then use json_encode(); to return the array to a JSON encoded string.
Also, use array_key_exists() rather than comparing array key strings.
$array = json_decode($json);
if(array_key_exists("job_payload_hash", $array){
$array["job_payload_hash"] = base64encode($var);
}
$json = json_encode($array);

Related

How to create a dynamic JSON array in PHP using multiple for eaches?

I need to generate a JSON Object and push it to a JSON object array using PHP.
This is my code.
public function getJSONData()
{
$csv = $this->getCsvData();
$finalArray = array();
// First foreach to iterate the data array.
foreach ($csv["data"] as $key => $value) {
// Second foreach to iterate the headlines array.
$newArray = array();
foreach ($csv["headlines"] as $index => $headline) {
// $newArray[$key]->$csv["headlines"] = $value;
// print_r($headline);
// print_r($value[$index]);
// echo " ";
array_push($newArray, array($headline => $value[$index]));
}
echo json_encode($newArray);
echo "<br>";
array_push($finalArray, json_encode($newArray));
}
// dd($finalArray);
}
From this code, I'm getting the following response.
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":349.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":349.95}]
[{"ID":12350},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12350},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
But it is not a valid JSON and I really need to get an output like this:
[{"ID":12348,"Status":1,"Manufacturere_ID":101,"Famiy_matchcode":"101-iphone-11","Name":"iPhone 11","Price":639.95}, {"ID":12348,"Status":1,"Manufacturere_ID":101,"Famiy_matchcode":"101-iphone-11","Name":"iPhone 11","Price":509.95}]
This is a standard JSON object array.
In my code, I'm using array_push($newArray, array($headline => $value[$index])); to generate the array and take it as JSON.
Please help me on this.
You seem to be creating arrays and adding json data in several places, build the data as a normal array and then encode the result...
// Foreach to iterate the data array.
foreach ($csv["data"] as $key => $value) {
// Combine headers with data and add to final result
$finalArray[] = array_combine($csv["headlines"], $value);
}
echo json_encode($finalArray);

How to echo value of "id"?

{"2b44928ae11fb9384c4cf38708677c48":{
"id":"115",
"qty":3,
"option":"{\"color\":{\"title\":\"Color\",
\"value\":\"\"
}
}",
"price":150,
"name":"Nightwear",
"shipping":"5",
"tax":3,
"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg",
"coupon":"",
"rowid":"2b44928ae11fb9384c4cf38708677c48",
"subtotal":450
}
}
Hello everyone,
This is my array and I want to echo value of only "id" i.e. I want to get value as '115' of key- "id". Please guide me how to make a foreach for this one? I have tried lots of variations but none worked :(
TIA :)
UPDATE-
I have tried this but did not get any result:
foreach($res as $k=>$t)
{
echo $t["product_details"]["id"];
}
Before you can use the JSON as an array you need to convert it first. use json_decode() for that.
<?php
$json='{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}';
$array = json_decode($json, true);
foreach($array as $key=>$value){
echo $value['id'];
}
?>
Assuming you have an array of objects like you provided in your post, I have put your object in an array for testing
<?php
$json = '[{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}},'.
'{"2b44928ae11fb9384c4cf38708677c48":{"id":"116","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}]';
$json = json_decode($json);
foreach ($json as $object){
$propsArray = get_object_vars($object);
reset($propsArray);
echo $object->{key($propsArray)}->id . "<br>\n";
}
exit;
this outputs
115
116
try a live demo (https://eval.in/836364)
$json='{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}';
$array = json_decode($json, true); // convert json string to array
$result = array_column($array, 'id'); // find matching array key and return values in array
foreach ($result as $value) { // echo each value with foreach loop
echo $id . '<br>';
}

Read and print json array in php

I have a JSON array like below. I want to print only the values of the name. But I am getting undefined index name and getting value of name.below is my json.
[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]
my code
foreach($doc_array as $data => $mydata)
{
foreach($mydata as $key=>$val)
{
echo $val['name'];
}
}
How to get the values of name from docProfile? Any help would be greatly appreciated
Inside your foreach you don't need to loop again since docProfile is an index of the json object array
Just simple access it
echo $mydata['docProfile']['name'].'<br>';
so your foreach would be like this
foreach($doc_array as $data => $mydata) {
echo $mydata['docProfile']['name'].'<br>';
}
Demo
Try to something Like this.
<?php
$string = '[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';
$arr = json_decode($string, true);
echo $arr[0]['docProfile']['name'];
?>
This array just have one row but if your array have more row you can use it;
you need to decode JSON at first.
$doc_array =json_decode($doc_array ,true);
foreach($doc_array as $key=> $val){
$val['docProfile']['name']
}
<?php
$json_str='[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';
$json_arr = (array)json_decode($json_str,true);
foreach($json_arr as $iarr => $ia)
{
foreach($ia["docProfile"] as $doc => $docDetails)
{
if($doc =="name")
{
echo $ia["docProfile"]["name"];
}
}
}
?>
This code gives you the answer

PHP check variable if exists in array of json

Array : [{"ID":1},{"ID":2}]
$id=1;
I want to check if $id exists in the array.
Thank you!
You may try Laravel's Collection::contains method, for example:
$collection = collect(json_decode($jsonString, true));
if ($collection->contains(1) {
// Exists...
}
Also, you may use key/value pair like this:
if ($collection->contains('ID', 1) {
//...
}
Also, if you want to get that item from the collection then you may try where like this:
$id = $collection->where('ID', 1)->first(); // ['ID' => 1]
You have a json formatted array and you need to decode it using json_decode first. After that loop the array to check for the id that you want.
So the code should look like this:
$json = '[{"ID":1},{"ID":2}]';
$id = 1;
$data = json_decode($json, true);
foreach($data as $item){
if($item['id'] == $id) {
echo 'it exists';
}
}
Iterate the array using for loop and use the value as a param to json_decode.
$id = 1;
$arr = array('{"ID":1}', '{"ID":2}');
foreach($arr as $val) {
if (in_array($id, json_decode($val, TRUE))) {
echo "id present";
}
}
Try this, if value is exist it will give key of array
$jsondata = '[{"ID":1},{"ID":2}]';
$array = json_decode($jsondata,true);
$key = array_search(1, array_column($array, 'ID'));
Just check if the string is in the json array, with little computation.
I think it's the more efficient way. Check the result here.
<?php
$id = 1;
$array = ['{"ID":1}', '{"ID":2}'];
echo in_array(json_encode(["ID" => $id]), $array) ? 'Yes' : 'No';

JSON and Arrays mixed up (in PHP)

This is what I get from my SQL selection. The data is correct, now I'd like to echo it by foreach.
Array ( [0] => stdClass Object ( [sql_column] => [{"1":"value1", "2":"value2", "3":"value3"}] ) )
What I've tried (and which didn't work) was:
$obj = json_decode($arr);
foreach($obj as $data){
echo $data->sql_column->1; //this should echo "value1", but it doesn't
}
Does anyone see my mistake? Thanks in advance!
If $arr is the array you posted then you can't json_decode it since it's an array and not a JSON string.
//First you need to get the string
$json = $arr[0]->sql_column;
//Then decode
$data = json_decode($json);
//Then loop
foreach($data as $key => $value){
echo "$key = $value \n";
}
Your json seems to be complicated (double dimensional array), but you can fetch values from it in this manner:
foreach($arr as $data){
$json = json_decode($data->sql_column);
$temp = (array)$json[0];
foreach($temp as $k=>$v){
print($v."<br/>");
}
}
I hope you get an idea...
I used foreach for $arr to cover multi values, you can omit that if you want:
$data=$arr[0];
$json = json_decode($data->sql_column);
$temp = (array)$json[0];
foreach($temp as $k=>$v){
print($v."<br/>");
}

Categories