I have called a JSON array from an API and used json_decode to assign them to a PHP variable.
The array looks like this:
[
{
"id": "1",
"abbr": "XXX",
"title": "YYY",
"visible_from_lat": "85",
"visible_to_lat": "-75",
},
{
"id": "2",
"abbr": "AAA",
"title": "BBB",
"visible_from_lat": "85",
"visible_to_lat": "-75",
}
]
The array has approx 50 items in total, all of which have a visible_from_lat and a visible_to_lat. What I need to do is group each items like so:
visible_from_lat > 0 then assign to variable1
visible_from_lat < 0 then assign to variable2
Any idea's how I do this?
Here there is a basic solution, assuming that in data.json file there are your json data:
<?php
$array = json_decode(file_get_contents("data.json"));
$resulSetPositive = [];
$resulSetNegative = [];
foreach ($array as $obj) {
if(isset($obj->visible_from_lat)) {
if($obj->visible_from_lat > 0) {
$resulSetPositive[] = $obj; // add obj to positive result set
}
else if($obj->visible_from_lat < 0) {
$resulSetNegative[] = $obj; // add obj to negative result set
}
}
}
file_put_contents("negative.json", json_encode($resulSetNegative, JSON_PRETTY_PRINT));
file_put_contents("positive.json", json_encode($resulSetPositive, JSON_PRETTY_PRINT));
Related
The existing code looks like this:
function getList(){
$sql = 'SELECT DISTINCT `person`.`person_name` as name, `skill`.`skill_name` as
skill,`skill_linker`.`skill_score`;
$result = $GLOBALS['conn']->query($sql);
if ($result->num_rows > 0) {
$emptyArray = array();
while($row = $result->fetch_assoc()) {
$emptyArray[] = $row;
}
echo json_encode($emptyArray);
}
}
JSON Output from above function:
[{
"name":"Bob Sun",
"skill":"Dancing",
"skill_score":"3"
},
{
"name":"Bob Sun",
"skill":"Surfing",
"skill_score":"2"
},
{
"name":"Bob Sun",
"skill":"Swimming",
"skill_score":"5"
},
{
"name":"Joe Steel",
"skill":"Eating",
"skill_score":"2"
},
{
"name":"Joe Steel",
"skill":"Cooking",
"skill_score":"3"
}]
Instead, I would like the JSON output to look something like this:
[
{
"name": "Bob Sun",
"skills" : [
"Dancing": 3,
"Surfing": 2,
"Swimming": 5
]
},
{
"name": "Joe Steel",
"skills" : [
"Eating": 2,
"Cooking": 3
]
}
]
Can this be done? How can I have it display skills:skill_score for each person if the data coming from the SQL result set is separate? How can I change the code to restructure the JSON data to have semi-categories?
Just transform the array in your while cycle.
while($row = $result->fetch_assoc()) {
$emptyArray[$row['name']]['name'] = $row['name'];
$emptyArray[$row['name']]['skills'][$row['skill']] = $row['skill_score'];
}
Welcome to StackOverflow.
insted of applying json_encode on the final array ,
apply it on row
concatinate all rows
inset final concatinated string into array
this may solve the issue
hello i have json file which contain like this data
{
"data": [
{
"SN": "210477",
"name": "jane",
"stdcode": "446515",
"total": 611
},
{
"SN": "210474",
"name": "JOHN doe",
"stdcode": "446512",
"total": 610
},
{
"SN": "210475",
"name": "smith doe",
"stdcode": "446513",
"total": 610
},
{
"SN": "210476",
"name": "omar",
"stdcode": "446514",
"total": 610
}
]
}
as you can see there is duplicate in total in the last three data in total which is 610
i want to order this data according to "total" so it be printed like this
1.jane
2.JOHN doe
2.smith doe
2.omar
i have this code that order it but this not what i want
<?php
$get_records = #file_get_contents('./result.json',true);
$decode_records = json_decode($get_records);
$data = $decode_records->data;
usort($data, function($a, $b) {
return $a->total > $b->total ? -1 : 1;
});
for($x=0;$x<=count($data);$x++){
echo $x+1 .".".$data[$x]->name;
}
?>
the code output
1.jane
2.JOHN doe
3.smith doe
4.omar
Check whether the total has changed, and don't increment the rank if not.
$rank = 0;
$last_total = null;
foreach ($data as $d) {
if ($d->total !== $last_total) {
$rank++;
$last_total = $d->total;
}
echo "$rank. {$data->name}<br>";
}
Note that this means that the next index after all the duplicates will be ranked #3. If you want it to jump to 5 you need to use the array index as well.
$last_total = null;
foreach ($data as $i => $d) {
if ($d->total !== $last_rank) {
$rank = $i+1;
$last_total = $d->total;
}
echo "$rank. {$data->name}<br>";
}
I have a nested JSON. I wanted to convert it to simple json in php
var movies = [{
"name": "Ice Age 3",
"place" : "USA",
"actors" : "cartoon",
"details": [
{"language": "English", "year": "2012"},
{"language": "French", "year": "2011"},
{"language": "German", "year": "2013"}
],
"details2": [
{"language2": "Spanish", "year2": "2015"},
{"language2": "Arabic", "year2": "2016"},
{"language2": "Hindi", "year2": "2017"}
]
}];
like this...
var movies = [
{"name":"Ice Age 3","place" : "USA", "actors" : "cartoon", "details.language":"English", "details.year":"2012", "details2.language2":"English", "details2.year2":"2015"},
{"name":"Ice Age 3","place" : "USA", "actors" : "cartoon", "details.language":"French", "details.year":"2011", "details2.language2":"French", "details2.year2":"2016"},
{"name":"Ice Age 3","place" : "USA", "actors" : "cartoon", "details.language":"German", "details.year":"2013", "details2.language2":"German", "details2.year2":"2017"}
];
When i tried this way, i am getting a flat json .
function convert_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$arrayList=convert_flatten($value);
foreach ($arrayList as $listItem) {
$result[] = $listItem;
}
}
else {
$result[$key] = $value;
}
}
return $result;
}
This actually is a representation json. Iam looking for a generic answer.
Any help will be appreciated
Thanks
Similar to Prashant's answer...
$movies = '[{
"name": "Ice Age 3",
"details": [
{"language": "English", "year": "2012"},
{"language": "French", "year": "2011"},
{"language": "German", "year": "2013"}
]
}]';
$movies = json_decode($movies, true);
$out = array();
foreach ( $movies as $movie ) {
foreach ( $movie['details'] as $movieDetails ){
$movieDetails['name'] = $movie['name'];
$out[] = $movieDetails;
}
}
echo json_encode($out);
Outputs...
[{"language":"English","year":"2012","name":"Ice Age 3"},
{"language":"French","year":"2011","name":"Ice Age 3"},
{"language":"German","year":"2013","name":"Ice Age 3"}]
Rather than trying to manipulate the content as some sort of anonymous JSON, this code just works with the data presented. Each element within the original JSON is processed one at a time (potentially allowing multiple movies with the same structure to be present) and just promotes each of the details array elements to the top level in $out (adding the name of the film into this each time).
try this
$(function () {
var movies = [{
"name": "Ice Age 3",
"details": [
{"language": "English", "year": "2012"},
{"language": "French", "year": "2011"},
{"language": "German", "year": "2013"}
]
}];
var obj = JSON.parse(JSON.stringify(movies));
var obj2;
jsonObj = [];
for (var i = 0; i < obj.length; i++) {
item = {};
obj2 = JSON.parse(JSON.stringify(obj[i].details));
for (var j = 0; j < obj2.length; j++) {
item ["name"] = obj[i].name;
item ["language"] = obj2[j].language;
item ["year"] = obj2[j].year;
jsonObj.push(item);
}
}
var data = JSON.stringify(jsonObj);
alert(data);
});
You don't need to recurse to do this, this is untested but will give a grounding for what you need;
function flattenMovies($data)
{
// Get the name of the movie
$name = $data['name'];
$return_val = array();
// For each part of this...
foreach ($data as $part)
{
// If it is an array...
if (is_array($part))
{
// Create a new array for this row and add the movie name
$add_parts = array("name" => $name);
// For each of the parts parts...
foreach ($part as $key => $value)
{
// Add this to the row array assoc by key = value
$add_parts[$key] = $value;
}
// Add the row to the return array
$return_val[] = $add_parts;
// Blank this row so we know this does not have any "old" info in
$add_parts = null;
}
}
// Return the flattened array
return $return_val;
}
All you need to do is traverse the array and add the parts to a single array of values
You may need to add another nesting into the foreach, as I say, untested
I have one combined array of order and its items combined into one array but i am trying to create json structure like order then its items list like wise.
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'abc',"price"=>250);
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'xyz',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'pqr',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'lmn',"price"=>250);
Output should be like
[
"0":[
{
"OrderNo": "1",
"partycode": "10",
"OrderDetails": [
{
"Item": "abc",
"price": 250
},
{
"Item": "xyz",
"price": 250
}
]
}
],
"1":[
{
"OrderNo": "2",
"partycode": "20",
"OrderDetails": [
{
"Item": "pqr",
"price": 250
},
{
"Item": "lmn",
"price": 250
}
]
}
]
]
This is What i Tried
$mainarray = array();
$orderarray = array();
$orderitemarray = array();
if (count(combinedarray) > 0) {
foreach (combinedarray as $obj) {
$orderarray[] = array("orderid" => $obj->orderid);
$orderitemarray[] = array("Item" => $obj->Item, "price" => $obj->price);
}
}
$mainarray[] = array_unique($orderarray);
$mainarray['OrderDetails'] = $orderitemarray;
echo json_encode($mainarray);
$mainarray = array();
foreach ($combinedarray as $x) {
$id = $x['orderid'];
unset($x['orderid']);
if (! isset($mainarray[$id])) {
$mainarray[$id]['OrderNo'] = $id;
}
$mainarray[$id]["OrderDetails"][] = $x;
}
// Now $mainarray has indexes equal to OrderNo. To count it from zero, use array_values
echo json_encode(array_values($mainarray), JSON_PRETTY_PRINT);
demo
By your given array
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'abc',"price"=>250);
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'xyz',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'pqr',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'lmn',"price"=>250);
Here is my solution for this
$new = array();
foreach($combinedarray as $r){
$new[$r['orderid']]['orderid'] = $r['orderid'];
$new[$r['orderid']]['partycode'] = $r['partycode'];
$new[$r['orderid']][] = array("item"=>$r['item'],"price"=>$r['price']);
}
$json = json_encode($new);
echo '<pre>';print_r($new);
echo $json;
suppose I have an Array like this :
$myArray =
[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]
Each element of array has json format. and now I want to get name of element that have id of 87 for example.
Firstly How can I found that is there element with this id then get name property of that?
Decode JSON string into array. Then use Laravel's array_first method.
<?php
$myArray = '[{"id": 86,"name": "admin/login"},{"id": 87,"name": "admin/logout"},{"id": 88,"name": "admin/desktop"}]';
// Decode into array
$array = json_decode($myArray, true);
// Find item with correct id
$result = array_first($array, function($key, $value){
return $value['id'] === 87;
}, false);
if ($result) {
echo 'Item found, it\'s name is: '.$result['name'];
}
If you have id you like to find in variable, you have to use use construct.
// ID to search for
$searchID = 87;
// Find item with correct id
$result = array_first($array, function($key, $value) use($searchID){
return $value['id'] === $searchID;
}, false);
Try using this:
$newArray = json_decode($myArray);
and you'll get type of array
[
[
"id"=> 86,
"name"=> "admin/login"
],.....
........
]
Your $myArray is incorrect so, assuming it is a json string you can do this in the following way :
At first json_decode it into an arry.
Loop through the elements to find out you desired value(87).
Keep a flag which will tell if you have actually found any value.
<?php
$myArray =
'[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]';
$myArray = json_decode($myArray , true);
$found = 0;
foreach($myArray as $anArray)
{
if($anArray['id'] == 87)
{
var_dump($anArray['name']);
$found = 1;
}
}
if($found == 1)
{
var_dump("Element found.");
}
else
{
var_dump("Element not found. ");
}
?>