PHP foreach json_encode issues - php

I got problems with json_encode.
My code below:
$jsonfiles = array('http://example.com/myjsonishere.php'); //Here's my JSON
foreach ( $jsonfiles as $jsonfile ) {
//read the json file contents
$jsondata = file_get_contents($jsonfile);
//convert json object to php associative array
$data = json_decode($jsondata, true);
$json = json_decode(stripslashes($data));
foreach ((array)$json as $u => $z){
foreach ($z as $n => $line){
//get the tweet details
$grap_item1 = $line['grap1'];
$grap_item2 = $line['grap2'];
$grap_item3 = $line['grap3'];
// execute this insertion
mysqli_stmt_execute($stmt);
}
}
}
Without that stripslashes, json_last_error would show error number 4 but now it's 0, so I'm good to go.
Without (array) in first foreach PHP error pop up:
Invalid foreach argument
Even if I have tested after $json = json_decode(stripslashes($data)); line : if(is_array($json)) the test is TRUE but still the foreach will not work without (array)
Anyway, in theory, my code passes the first foreach, but if I put inside first foreach loop e.g. var_dumb($z) or whatever, it will not print anything. So I guess my code is stuck in the first foreach.
Please, let me know if I could provide more information.

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 edit JSON objects

I'm on PHP and I need to edit a JSON output to return only objects >=0 and divided by one hundred
Eg.
$json = {"data":[0,55,78,-32,-46,37]}
Needed
$json = {"data":[0,0.55,0.78,0.37]}
How this can be done?
Well, I know this is not the best practice, but if it's as simple as this, you can do the following.
$json = '{"data":[0,55,78,-32,-46,37]}';
// decoding the string to objects & arrays
$x = json_decode($json);
// applying a function on each value of the array
$x->data = array_map(
function($a)
{
if( $a >= 0 ) return $a/100;
else return null;
},
$x->data
);
// Removing empty values of the array
$x->data = array_filter($x->data);
// making a JSON array
$jsonData = json_encode(array_values($x->data));
// inserting a JSON array in a JSON Object
$json = '{"data":' . $jsonData . '}';
// here is your {"data":[0,0.55,0.78,0.37]}
echo $json;
Hope it helps !
Btw, I had to trick the json encode with array_values to prevent the creation of an object rather than an array for the data content. But I guess there is a better method that I just don't know ...
EDIT :
Find out the way :D
Once empty values removed from the array, just do :
$x->data = array_values($x->data);
$json = json_encode($x);
This will do the trick and it will not create issues with the rest of the object.
Alessandro:
Here's my approach, feel free to try. json_decode and a simple foreach can help you...
Code:
$json = array();
$result = array();
$json = '{"data":[0,55,78,-32,-46,37]}';
$decoded_json=json_decode($json, TRUE);
foreach ($decoded_json['data'] as &$value) {
if ($value >= 0){
$value = $value / 100;
$result[]=$value;
}
}
echo json_encode($result);
?>
Result:
[0,
0.55,
0.78,
0.37
]

Decoding json in array , editing array and encoding in json - 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);

looping through an array in : PHP

My JSON Array:
[\"{\\\"mapurl\\\":\\\"http:\\\\\\/\\\\\\/maps.google.com\\\\\\/maps?q=17.xxxxx5,78.xxxxxx3\\\",\\\"caller\\\":\\\"+91xxxxxx\\\",\\\"id\\\":1,\\\"reciever\\\":\\\"+91xxxxxx\\\",\\\"timpestamp\\\":\\\"3\\\"}\",\"{\\\"mapurl\\\":\\\"http:\\\\\\/\\\\\\/maps.google.com\\\\\\/maps?q=17.xxxxx,78.xxxxx\\\",\\\"caller\\\":\\\"+91xxxxxx\\\",\\\"id\\\":2,\\\"reciever\\\":\\\"+91xxxxx\\\",\\\"timpestamp\\\":\\\"3\\\"}\"]
I am passing this JSONArray as a part of POST Request in add Parameter.
My code for displaying the content of the Array
$jsonData = stripslashes($_POST['add']);
$phpArray = json_decode($jsonData,true);
foreach ($phpArray as $index => $record)
{
echo $record["caller"];
}
My Output is just two open curly brackets.
{{
I unable to understand whats wrong
Your JSON is invalid, There shouldn't be quotes around each array.
Fix what is generating it, if oyou cant the below will fix
$jsonData = stripslashes(stripslashes($jsonData));
$jsonData = str_replace(
array('"{', '}"'),
array('{', '}'),
$jsonData
);
$phpArray = json_decode($jsonData,true);
foreach ($phpArray as $index => $record)
{
echo $record["caller"];
}
Though use as a last resort, Fix the broken JSON before its sent is the best option. magic quotes is also removed from PHP. avoid using it
Output of above
+91xxxx+91xxxxx
You have problem with your json sting.
Try this :
$post = '[{\\\"mapurl\\\":\\\"http:\\\\\\/\\\\\\/maps.google.com\\\\\\/maps?q=17.xxxxx5,78.xxxxxx3\\\",\\\"caller\\\":\\\"+91xxxxxx\\\",\\\"id\\\":1,\\\"reciever\\\":\\\"+91xxxxxx\\\",\\\"timpestamp\\\":\\\"3\\\"},{\\\"mapurl\\\":\\\"http:\\\\\\/\\\\\\/maps.google.com\\\\\\/maps?q=17.xxxxx,78.xxxxx\\\",\\\"caller\\\":\\\"+91xxxxxx\\\",\\\"id\\\":2,\\\"reciever\\\":\\\"+91xxxxx\\\",\\\"timpestamp\\\":\\\"3\\\"}]';
$jsonData = stripslashes(stripslashes($post));
$phpArray = json_decode($jsonData,true);
foreach ($phpArray as $index => $record)
{
echo $record["caller"];
}

Simple Json in PHP

I have a simple task that does not work
I Have a json file..
When you decode with the 'true' bool as second param, you will get an associative array back. In your code snippet you then loop it out.
What you should do, is skip the loop and just access the data from the assoc array right away:
echo $array['navn'];
// The JSON object:
{"nr":"5250","navn":"Odense SV","adresser":"http://oiorest.dk/danmark/postdistrikter/5250/adresser"}
// Is equivalent to this php assoc-array:
array("nr" => "5250", "navn" => "Odense SV", "adresser" => "http://oiorest.dk/danmark/postdistrikter/5250/adresser");
try following
<?php
$url = "http://oiorest.dk/danmark/postdistrikter/5000.json";
$content = file_get_contents($url);
$array = json_decode($content, true);
foreach ($array as $key=>$val) {
echo $val;
}
?>

Categories