PHP encode json 3 in 1 response - php

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.

Related

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>";

convert numerically indexed associative-array in PHP, to valid JavaScript Object via JSON

Let's say you have a numerically indexed array that looks like this (obtained via RedBeanPHP's find operation):
[
[33=>["name"=>"John", "age"=25]],
[55=>["name"="Jane", "age"=23]]
]
where 33 and 55 are id's of each of the 2 "beans" (basically associative-arrays).
And you want to convert the array to JSON so you can send it to a JavaScript client and use the data there as a JavaScript Object.
But you can't simply JSON_encode this because you'll end up with numerical keys in a JavaScript Object, and JavaScript doesn't like that.
What strategy can you use to convert this array to a JavaScript Object via JSON so that all the data (including id of each bean) is available at the JavaScript end? (To the RedBeanPHP folks out there: I'm hoping there's a native RedBeanPHP way to do this that I haven't found yet.)
One option is using array_map to loop thru the array. Use array_values to get all the values from the array and indexes the array numerically.
$arr = [
[33=>["name"=>"John", "age"=>25]],
[55=>["name"=>"Jane", "age"=>23]]
];
$result = array_map(function($o){
return array_values($o)[0];
}, $arr);
echo json_encode( $result );
This will result as:
[{"name":"John","age":25},{"name":"Jane","age":23}]
Simple. You should try this. First iterate through the outer array and inside that get the key i.e id of the data. Add id to other values and push that array into resultant one.
$result = array();
$arr = [[33=>["name"=>"John", "age"=>25]],[55=>["name"=>"Jane", "age"=>23]]];
foreach ($arr as $ar) {
foreach ($ar as $key => $value) {
$value['id'] = $key;
array_push($result, $value);
}
}
echo json_encode($result);
Output :-
[{"name":"John","age":25,"id":33},{"name":"Jane","age":23,"id":55}]
For your associative array:
$array = array(33 => array("name" => "John", "age" => 25), 55 => array("name" => "Jane", "age" => 23));
PHP json_encode function:
$good_json = json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
Produces JSON for JavaScript object (string "name" : value pair):
{"33":{"name":"John","age":25},"55":{"name":"Jane","age":23}}

json decode/encode repeated array

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).

PHP: Give a name to an array of JSON objects?

I have managed to get data from database in PHP file.
From there(data.php),
$output = json_encode($result);
The result would be like this,
$output=[{"kitty":"Whitely"},{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]
So how do I give name "kitten" an array of kitty objects in php format?
For example like
"kitten":[{"kitty":"Whitely"},{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]
You have to wrap your result in another array on the 'kitten' key :
$output = json_encode(['kitten' => $result]);
Try this:
<?php
$kitty = array('kitten' => array());
$kitty['kitty'][] = array('kitty' => 'Tabby');
$kitty['kitty'][] = array('kitty' => 'Ruby');
$kitty['kitty'][] = array('kitty' => 'Silver');
var_dump($kitty);
var_dump(json_encode($kitty));
which results in: {"kitty":[{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]}
Use nested encode and decode
$json = '[{"kitty":"Whitely"},{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]';
echo json_encode(array('kitten' => json_decode($json)));
try to use this
$output['kitty'][] = json_encode($result);
$result =array('kitten'=> $output);
output
{
"kitten":[
{"kitty":"Whitely"},
{"kitty":"Tabby"},
{"kitty":"Ruby"},
{"kitty":"Silver"}
]
}

How to format JSON output to display only values in quotes and not keys?

This is related to Need to display only array value in JSON output asked earlier.
I just want to show only values like
[
"autoComplete",
"ColdFusion",
"jQuery Mobile"
];
Background:
I am using and AJAX call via Jquery mobile to retrieve data from server (language:PHP). I want to use https://github.com/commadelimited/autoComplete.js in my Phonegap Application.
Please advice! I am new to JSON.
when using json_encode, any array that has a zero based numeric index (meaning it is not an associative array and starts with 0 and is not missing any numbers) will be converted to a javascript array instead of a js object literal. You can use array_values in php to get all the values from an array numerically indexed.
<?php
//a generic array
$a = array(
'foo'=>'bar',
'one'=>'two',
'three'=>'four');
//display the array in php
var_dump($a);
echo '<br>';
//json encode it
$json = json_encode($a);
var_dump($json);
echo '<br>';
//json encode just the values
$json = json_encode(array_values($a));
var_dump($json);
http://codepad.viper-7.com/hv06zn
Thanks Jonathan.
However I found the solution as below. I hope that it is useful to someone else too.
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row["title"];
}
mysql_close($con);
echo json_encode($records);

Categories