json decode/encode repeated array - php

hey ive managed to decode the encode json i created but when i try to print the decoded array it repeats the same username ( the last one on the list ) over and over again. what i want is that all the users are desplayed
this is the code for the encoded json array
$query =
"SELECT
userid,
username,
password,
email
FROM Users ORDER BY userid";
$results = mysqli_query($connection,$query);
The encoded array code below
<?php
echo "Data with Json Encoding";
foreach($results as $row){
$encode = json_encode($row, true);
echo '<pre>';print_r($encode); echo '</pre>';
}
?>
the decoded array code below
<?php
echo "Data with Json Decoding";
foreach($results as $row){
$decode = json_decode($encode, true);
echo '<pre>'; print_r($decode);'</pre>';
}
this is the result of the code Data with Json Decoding
Array
(
[userid] => 239
[username] => desposit4221
[password] => 699e5fae54df4c82314e42dd86c4d383
[email] => ad471993#hotmail.com
)
Array
(
[userid] => 239
[username] => desposit4221
[password] => 699e5fae54df4c82314e42dd86c4d383
[email] => ad471993#hotmail.com
)
it's this over and over again, it should be the list of my users
any help would be greatly appreciated

echo "Data with Json Encoding";
$encodedResults = array();
foreach($results as $row){
$encode = json_encode($row, true);
echo '<pre>';print_r($encode); echo '</pre>';
$encodedResults[] = $encode;
}
?>
echo "Data with Json Decoding";
foreach($encodedResults as $row){
$decode = json_decode($row, true);
echo '<pre>'; print_r($decode);'</pre>';
}

If you put the line
$encode = json_encode($row, true);
into your second loop just after the foreach line, you should get the results you expect. It's a reasonable way to explore the datamanagement aspects of php. Good luck in your projects!

Encode your array:
echo "Data with Json Encoding";
$encoded_datas = json_encode($results);
echo $encoded_datas;
Decode the string into an array:
echo "Data with Json Decoding";
$decoded_datas = json_decode($encoded_datas, true);
echo '<pre>';
print_r($decoded_datas);
echo '</pre>';
You don't need to encode (and then decode) your array row by row.
Plus, as explained in comments and as shown in costa's answer, your code didn't work because you were decoding the same string each time: your $encoded variable contains the last value you put in it (the last row you encoded).

Related

Foreach json output and store in variables

I am trying to foreach the result from a json code.
I have checked the json result at jsonlint and it's validated.
I do this:
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
Then when i do echo $result this is the result:
{"vat":{"640252":{"name":"0%","percentage":"0.00","invoice_type":"2","vat_code":"5B2","available":"1"},"640258":{"name":"0%","percentage":"0.00","invoice_type":"1","vat_code":"1E1","available":"1"},"640256":{"name":"21%","percentage":"21.00","invoice_type":"1","vat_code":"1A2","available":"1"}}}
when i do this it does show the name of vat code 640252:
$result2 = json_decode($result, true);
echo $result2['vat']['640252']['name'];
But i cannot go through the json with a foreach. To start would like to make a variable with the id (like 640252) and one with the percentage, and echo them in the foreach.
I have tried a lot of things from Stackoverflow but all the json output seems to look different from the output that i have.
I hope that someone can help me in the right direction.
The reson is, that the vat is a key with a value array after decoding the json string. Just iterate the vat property as in the following example.
$data = json_decode($result, true);
foreach ($data['vat'] as $id => $item) {
echo "<pre>";
var_dump($id, $item);
echo "</pre>";
}
Hope that helps.
<?php
$json = '... lots of JSON here ...';
$arr = json_decode($json, true);
foreach ($arr['vat'] as $id => $item) {
echo "$id -> {$item['name']}\n";
}
Using your JSON as an example, this is the output that I get:
640252 -> 0%
640258 -> 0%
640256 -> 21%
If you don't need the ID (e.g. 640252) you can just do:
foreach ($arr['vat'] as $item) {
Firstly I would suggest to format your json to be readable for you. Personally I use https://jsonlint.com/ to validate my json data.
If we do that, we can see that vat is a json object which haves those 640252, 640258 etc as direct child's.
Decoding with second parameter as true, will decode as associative array. Looping over the vat properties would be:
foreach($result2['vat'] as $id => $val) {
echo 'Id is:'. $id;
echo 'name is '. $val['name'] ;
echo 'percentage is '. $val['percentage'] ;
}

Storing array in db

I need to create an array of keys and store it in a db table.
$myArr = array();
foreach($keys AS $key) {
$myArr[$r->id] = $r->key;
}
before storing it I serialize it
$db_arr = serialize($myjArr);
Later I need to get the stores array and loop through it to perform some action. However, when I unserialize stored array and do print_r my output looks like this:
Array ( [5981] => 7u7Dj [5982] => mVmx4 )
It appears that the array is malformed. What am I missing?
You should take a look at this, I think you may need to unserialize the data before trying to use it php unserialize
$array = unserialize($serialized_array);
Here is an example
$original = [
"who" => "you",
"me" => "yes"
];
echo "<pre>";
print_r($original);
echo "</pre>";
$ser = serialize($original);
echo "<pre>";
print_r($ser);
echo "</pre>";
$un = unserialize($ser);
echo "<pre>";
print_r($un);
echo "</pre>";

PHP encode json 3 in 1 response

I have in a file 3 json responses. I need to encode them in one Json with 3 Objects inside which are the three responses which I have separated. Any help?-
echo json_encode(array('result_temperatura'=>$output_result_temperatura));
echo json_encode(array('result_presion'=>$output_result_presion));
echo json_encode(array('result_altitud'=>$output_result_altitud));
Build an array or object with the data:
$result = array('result_temperatura'=>$output_result_temperatura,
'result_presion'=>$output_result_presion,
'result_altitud'=>$output_result_altitud);
echo json_encode($result);
Or if you actually want a multidimensional array:
$result[] = array('result_temperatura'=>$output_result_temperatura);
$result[] = array('result_presion'=>$output_result_presion);
$result[] = array('result_altitud'=>$output_result_altitud);
echo json_encode($result);
Combine the array elements first,
$arr = array(
'result_temperatura' => $output_result_temperatura,
'result_presion' => $output_result_presion,
'result_altitud' => $output_result_altitud
);
Then encode,
echo json_encode($arr);
Hope this helps.

How to parse JSON array of objects in PHP

I am new to php programming. Here in my project I am trying to parse JSON data coming from php web service. Here is the code in web service.
$query = "select * from tableA where ID = 1";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$arr= array();
while ($row = mysql_fetch_assoc($result)) {
$arr['articles'][] = $row;
}
header('Content-type: application/json');
echo json_encode($arr);
}
else{
echo "No Names";
}
This is giving me data in this JSON format.
{"articles":[{"ID":"1","Title":"Welcome","Content":"This is the first article."}]}
Now here is my php page code.
<?php
$jfile = file_get_contents('http://localhost/api/get_content.php');
$final_res = json_decode($jfile, true) ;
var_dump( $final_res );
$content = $final_res->articles->Content;
?>
I want to show the content on webpage.
I know code at var_dump( $final_res ); is working. But after that code is wrong. I tried to look at many tutorials to find the solution but didn't find anyone. I don't know where I am wrong.
The second parameter of json_decode determines whether to return the result as an array instead of an object. Since you set it to true your result is an array and not an object.
$content = $final_res['articles'][0]['Content'];
As an alternative answer, if you want to use it as an object, use this code:
$a = '{"articles":[{"ID":"1","Title":"Welcome","Content":"This is the first article."}]}';
$final_res = json_decode($a);
echo '<pre>';
print_r($final_res);
echo '</pre><br>';
Note that I removed the second part (true) from the json_decode
Output:
stdClass Object
(
[articles] => Array
(
[0] => stdClass Object
(
[ID] => 1
[Title] => Welcome
[Content] => This is the first article.
)
)
)
Accessing Content:
echo 'Content: ' . $final_res->articles[0]->Content;
Output:
Content: This is the first article.
Run code

Get data from JSON array

I have this JSON array data:
[{"region":"Abersee","price":"1.298"},{"region":"Fuschl am See","price":"1.319"},{"region":"St. Gilgen","price":"1.317"},{"region":"Innerschwand","price":"1.321"},{"region":"Mondsee","price":"1.309"},{"region":"Abersee","price":"1.298"},{"region":"Mondsee","price":"1.309"},{"region":"Innerschwand","price":"1.321"},{"region":"Fuschl am See","price":"1.319"},{"region":"St. Gilgen","price":"1.317"},{"region":"Abersee","price":"1.298"},{"region":"Mondsee","price":"1.309"},{"region":"St. Gilgen","price":"1.317"},{"region":"Fuschl am See","price":"1.319"},{"region":"Innerschwand","price":"1.321"},{"region":"Abersee","price":"1.298"},{"region":"St. Gilgen","price":"1.317"},{"region":"Mondsee","price":"1.309"},{"region":"Fuschl am See","price":"1.319"},{"region":"Innerschwand","price":"1.321"},{"region":"Abersee","price":"1.298"},{"region":"Mondsee","price":"1.309"},{"region":"Fuschl am See","price":"1.319"},{"region":"St. Gilgen","price":"1.317"},{"region":"Innerschwand","price":"1.321"},{"region":"Abersee","price":"1.298"},{"region":"Fuschl am See","price":"1.319"},{"region":"Mondsee","price":"1.309"},{"region":"St. Gilgen","price":"1.317"},{"region":"Innerschwand","price":"1.321"}]
And I am not sure how to properly get the region and price data out. I tried this:
$array = json_encode($jsondata);
$json = json_decode($array, true);
echo $json['region'];
echo $json['price'];
But nothing appears. Any suggestions?
try this:
$array = json_encode($jsondata);
$json = json_decode($array, true);
foreach($json as $data){
echo $data['region'] . "<br>";
echo $data['price'] . "<br>";
}
The json_encode isn't needed, as you say - you already have that JSON data. Simply decode it, then loop over it. You are currently trying to access the first entry, but the conversion from JSON to PHP will add numeric indexes/array keys to the PHP array which don't exist in the JSON.
foreach over the array:
$jsondata = '[{"region":"Abersee","price":"1.298"},{"region":"Fuschl am See","price":"1.319"},{"region":"St. Gilgen","price":"1.317"},{"region":"Innerschwand","price":"1.321"},{"region":"Mondsee","price":"1.309"},{"region":"Abersee","price":"1.298"},{"region":"Mondsee","price":"1.309"},{"region":"Innerschwand","price":"1.321"},{"region":"Fuschl am See","price":"1.319"},{"region":"St. Gilgen","price":"1.317"},{"region":"Abersee","price":"1.298"},{"region":"Mondsee","price":"1.309"},{"region":"St. Gilgen","price":"1.317"},{"region":"Fuschl am See","price":"1.319"},{"region":"Innerschwand","price":"1.321"},{"region":"Abersee","price":"1.298"},{"region":"St. Gilgen","price":"1.317"},{"region":"Mondsee","price":"1.309"},{"region":"Fuschl am See","price":"1.319"},{"region":"Innerschwand","price":"1.321"},{"region":"Abersee","price":"1.298"},{"region":"Mondsee","price":"1.309"},{"region":"Fuschl am See","price":"1.319"},{"region":"St. Gilgen","price":"1.317"},{"region":"Innerschwand","price":"1.321"},{"region":"Abersee","price":"1.298"},{"region":"Fuschl am See","price":"1.319"},{"region":"Mondsee","price":"1.309"},{"region":"St. Gilgen","price":"1.317"},{"region":"Innerschwand","price":"1.321"}]';
$json = json_decode($jsondata, true);
foreach($json as $each)
echo $each['region'] . ': ' . $each['price'] . PHP_EOL;
Example
Edit: a print_r of the decoded array (as mentioned by Marcin Orlowski) would show you its structure in PHP, similar to this:
Array
(
[0] => Array
(
[region] => Abersee
[price] => 1.298
)
[1] => Array
(
[region] => Fuschl am See
[price] => 1.319
)

Categories