I have this
{"1":{"name":"cat"},"2":{"name":"elephant"}}
how to convert it to
[{"name":"dog"},{"name":"cat"}]
or convert it to vice versa
$arr = json_decode('{"1":{"name":"cat"},"2":{"name":"elephant"}}');
$result = array();
foreach($arr as $item) {
$data = ['name' => $item->name];
$result[] = $data;
}
$json = json_encode($result);
print_r($json);
Related
after json decode array merge
$permission_roles1 = DB::table('permission_roles')->select('permission_name')->first();
$permission_roles2 = DB::table('user_permissions')->select('userP_name')->first();
$json_array1 = json_decode($permission_roles1->permission_name);
$json_array2 = json_decode($permission_roles2->userP_name);
$arr1 = array($json_array1);
$arr2= array($json_array2);
$res = array_merge($arr1, $arr2);
dd($res);
In your code,
$json_array1 = json_decode($permission_roles1->permission_name);
$json_array2 = json_decode($permission_roles2->userP_name);
returns object not an array.
Just changed it to
$json_array1 = json_decode($permission_roles1->permission_name, true);
$json_array2 = json_decode($permission_roles2->userP_name, true);
convert array object into array then merge the array
$permission_roles1 = DB::table('permission_roles')->select('permission_name')->first();
$permission_roles2 = DB::table('user_permissions')->select('userP_name')->first();
$arr1 = (array) $permission_roles1->permission_name;
$arr2 = (array) $permission_roles2->userP_name;
$res = array_merge($arr1, $arr2);
dd($res);
I'm trying to add all the keys of different json available in a file to an array. What I did for the moment is this:
//Get the json file content
$jsonData = file(__DIR__ .'/../logs/error.json');
//Save all the json
$json = [];
//Iterate through the line of the file, each line is a json
foreach($jsonData as $line)
{
//Convert the json in an associative array
$array = json_decode($line, true);
//Iterate through the json keys
foreach($array as $k => $val)
{
$json[$k] = $val;
}
}
the json file is like this:
{"Timestamp":"2018-06-14T10:46:52.3326036+02:00","Level":"Error","MessageTemplate":"System.Exception"}
{"Timestamp":"2018-06-14T10:47:22.7493871+02:00","Level":"Error","MessageTemplate":"System.Exception"}
I'll get this:
{"Timestamp":"2018-06-14T10:47:22.7493871+02:00","Level":"Error","MessageTemplate":"System.Exception"}
because the $json[$k] override I guess the previous array, but $k is a new json so why the index of the array is replaced?
Thanks in advance for any help.
may be this one is your expected output.
//Get the json file content
$jsonData = file(__DIR__ .'/../logs/error.json');
//Save all the json
$json = [];
//Iterate through the line of the file, each line is a json
foreach($jsonData as $line)
{
//Convert the json in an associative array
$array = json_decode($line, true);
$temp = [];
//Iterate through the json keys
foreach($array as $k => $val)
{
$temp[$k] = $val;
}
$json[] = $temp;
}
change this line
foreach($array as $k => $val)
{
$json[$k] = $val;
}
to
foreach($array as $k => $val)
{
$json[][$k] = $val;
}
Well you're overwriting keys with the same names, so there's really nothing surprising in your output.
You probably meant to do this:
foreach($jsonData as $line) {
$tmp = []; //<-- set up a new array just for this iteration
$array = json_decode($line, true);
foreach($array as $k => $val) $tmp[$k] = $val;
$json[] = $tmp; //<-- log the array in the master $json array
}
//Get the json file content
$jsonData = file(__DIR__ .'/../logs/error.json');
//Convert the json in an associative array
$array = json_decode($jsonData, true);
//Save all the json
$json = [];
//Iterate through the line of the file, each line is a json
foreach($array as $k => $val)
{
$json[][$k] = $val;
}
The below is my php code.Many thanks
$data = array();
foreach ($row as $rowk) {
$data[] = array(
'message' => $row['traditionalmessage'],
'phone' => $row['telMobile']
);
break;
}
echo json_encode($data);
My current result
[{"message":"B\u578b\u809d\u708e\u75ab\u82d7\u4e0b\u4e00\u500b\u6ce8\u5c04\u671f\u4e3a2017-06-30\r\n","phone":"96709394"}][{"message":"\u75ab\u82d7\u540d\u7a314\u4e0b\u4e00\u500b\u6ce8\u5c04\u671f\u4e3a2017-06-30\r\n","phone":"96709394"}][{"message":"\u4fe1\u606f","phone":"55503234"}]
My desired result
[{"message":"B\u578b\u809d\u708e\u75ab\u82d7\u4e0b\u4e00\u500b\u6ce8\u5c04\u671f\u4e3a2017-06-30\r\n","phone":"96709394"},{"message":"\u75ab\u82d7\u540d\u7a314\u4e0b\u4e00\u500b\u6ce8\u5c04\u671f\u4e3a2017-06-30\r\n","phone":"96709394"},{"message":"\u4fe1\u606f","phone":"55503234"}]
In JSON arrays represented in [], and objects in {}, so in desired case you should have array of objects while you have array of arrays.
Try something like this:
$data = array();
foreach ($row as $rowk) {
$obj = new stdClass();
$obj->message = $row['traditionalmessage'];
$obj->phone = $row['telMobile'];
$data[] = $obj;
}
echo json_encode($data);
I am querying a service if a person have phone number(s) (also maybe not). I have a json string (as return value) like the following:
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
I convert this string to json_decode() function.
$jd = json_decode($json);
Then I want to get the phone numbers only into an array without keys.
if($jd->found) {
$o2a = get_object_vars($json);
}
var_dump($o2a);
When I want to see what $o2a holds with var_dump() function, I get the following:
array (size=2)
'data' =>
array (size=2)
0 =>
object(stdClass)[2]
public 'tel1' => string '1219' (length=4)
1 =>
object(stdClass)[3]
public 'tel2' => string '2710' (length=4)
'found' => boolean true
I want to get only the phone numbers into an array at the end like:
$phones = array('1219', '2710');
What makes me stop doing this is that I do not know how many phone numbers one can have. Json array could consist of more or less elements.
$possibleJson1 = '{"data":[],"found":false}'; //no phone number found
$possibleJson2 = '{"data":[{"tel1":"1102"},{"tel2":"3220"},{"tel3":"1112"},{"tel4":"3230"}],"found":true}'; //4 phone numbers found
It may vary 0-to-n, so if it was a constant number I could create that array within a loop.
Some functions without any code :)
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$vals = array_values(array_reduce(json_decode($json, true)['data'], 'array_merge',[]));
var_dump($vals);
Convert it into an array and then you should be able to iterate it easily
$jd = json_decode($json, true);
$phones = array();
if(isset($jd['data']) && $jd['found']) {
foreach($jd['data'] as $key => $val) $phones[] = $val;
}
Instead of handling with an object, use the second parameter of the json_decode function so it would returned an array.
Check if the data and found keys exist.
Since you don't know what are the keys names, you can use array_values
Demo
.
$jd = json_decode($json, true);
if(isset($jd['data']) && isset($jd['found'])){
$telArr = $jd['data'];
$phones = array();
foreach($telArr as $tel){
$value = array_values($tel);
$phones[] = $value[0];
}
var_dump($phones);
}
Output:
array(2) {
[0]=>
string(4) "1102"
[1]=>
string(4) "3220"
}
Well, I would try something like that:
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$jd = json_decode($json);
$phones = [];
if ($jd->found && count($jd->data)) {
foreach ($jd->data as $key -> $value) {
$phones[] = $value;
}
}
Try as using in_array and simple foreach loop
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$arr = json_decode($json, true);
$result = array();
if (in_array(true, $arr)) {
foreach ($arr['data'] as $key => $value) {
foreach($value as $k => $v)
$result[] = $v;
}
}
print_r($result);
Fiddle
I am querying a database for results and trying to convert them into JSON encodable array where the key will act as the name of the pair and the value is the value. How would I do this in the following code below?
foreach($results as $result) {
foreach( $result as $key => $value ) {
if ($key == 'D')
{
$trimmed = round($value, 4);
}
else
{
$trimmed = trim($value, "\n\r");
}
$array[$i] ="$key"."=>"."$trimmed";
}
$i = 0;
$jret = json_encode($array);
echo $jret;
}
For example:
<?php
$object[0] = array("foo" => "bar", 12 => true);
$encoded_object = json_encode($object);
?>
output:
{"1": {"foo": "bar", "12": "true"}}
dunno what you need and why you mimic PHP code instead of using it, but may be
$array[] = array($key => $trimmed);
is what you are looking for
with
$array[$i][$key] = $trimmed;
you could do
$return = json_encode($object, JSON_FORCE_OBJECT);
at the end