How to merge JSON two indexes and then Parse information - php

I am trying to iterate both index of JSON(Players and Buildings), so that i can a get new result in jQuery
I have two index of JSON one having information of Players and second index having information of Building related Player.
I want to Parse it so that i can get Player and its building name.
My Actual JSON result
{
"Players": [
{
"id": "35",
"building_id": "8",
"room_num": "101",
},
{
"id": "36",
"building_id": "9",
"room_num": "102",
},
{
"id": "37",
"building_id": "10",
"room_num": "103",
},
{
"id": "38",
"building_id": "11",
"room_num": "104",
}
],
"Buildings": [
{
"id": "8",
"name": "ABC"
},
{
"id": "9",
"name": "DEF"
},
{
"id": "10",
"name": "GHI"
},
{
"id": "11",
"name": "JKL"
}
]
}
Need this
"information": [
{
"player_id": "35",
"Buildings_name": "ABC"
},
{
"player_id": "36",
"Buildings_name": "DEF"
},
{
"player_id": "37",
"Buildings_name": "GHI"
},
{
"player_id": "38",
"Buildings_name": "JKL"
}
]
}

Here you go, this go for each player and check if there are buildings and will map them to new structure. This will not filter values for buildings that do not have mapping to players, and will not include the buildings with no players.
var x = {
"Players": [
{
"id": "35",
"building_id": "8",
"room_num": "101",
},
{
"id": "36",
"building_id": "9",
"room_num": "102",
},
{
"id": "37",
"building_id": "10",
"room_num": "103",
},
{
"id": "38",
"building_id": "11",
"room_num": "104",
}
],
"Buildings": [
{
"id": "8",
"name": "ABC"
},
{
"id": "9",
"name": "DEF"
},
{
"id": "10",
"name": "GHI"
},
{
"id": "11",
"name": "JKL"
}
]
};
var res = $.map(x.Players, function(item) {
return {
player_id: item.id,
building_name: $.grep(x.Buildings, function(i) {
return i.id == item.building_id
}).length != 0 ? $.grep(x.Buildings, function(i) {
return i.id == item.building_id
})[0].name : undefined
}
})
and if you want to filter values that do not have relationships e.g INNER join
var resInnerJoin = $.grep($.map(x.Players, function(item) {
return {
player_id: item.id,
building_name: $.grep(x.Buildings, function(i) {
return i.id == item.building_id
}).length != 0 ? $.grep(x.Buildings, function(i) {
return i.id == item.building_id
})[0].name : undefined
}
}), function(it) {
return it.building_name != undefined
})

If you need it in PHP :
$json = '{...}';
// create and PHP array with you json data.
$array = json_decode($json, true);
// make an array with buildings informations and with building id as key
$buildings = array();
foreach( $array['Buildings'] as $b ) $buildings[$b['id']] = $b;
$informations = array();
for ( $i = 0 ; $i < count($array['Players']) ; $i++ )
{
$informations[$i] = array(
'player_id' => $array['Players'][$i]['id'],
'Buildings_name' => $buildings[$array['Players'][$i]['building_id']]['name']
);
}
$informations = json_encode($informations);
var_dump($informations);

Related

Is it possible to edit the elements of a json array to accomodate additional data/elements?

I'm retrieving data from a database and pushing it to arrays then use json_encode() to output in json format. I have ended up having the data in this format.
[
{
"category_id": "1",
"category_name": "Construction Materials"
},
{
"items": [
{
"id": "1",
"item_name": "Wire Mesh",
"price": "459",
"image_url": null
},
{
"id": "2",
"item_name": "Cement",
"price": "700",
"image_url": null
},
{
"id": "3",
"item_name": "Barbed Wire",
"price": "3000",
"image_url": null
},
{
"id": "4",
"item_name": "Iron sheet",
"price": "200",
"image_url": null
}
]
},
{
"category_id": "2",
"category_name": "Plumbing"
},
Here is what I want to achieve:
[
{
"category_id": "1",
"category_name": "Construction Materials"
"items": [
{
"id": "1",
"item_name": "Wire Mesh",
"price": "459",
"image_url": null
},
{
"id": "2",
"item_name": "Cement",
"price": "40",
"image_url": null
},
{
"id": "3",
"item_name": "Barbed Wire",
"price": "3000",
"image_url": null
},
{
"id": "4",
"item_name": "Iron sheet",
"price": "200",
"image_url": null
}
]
},
{
"category_id": "2",
"category_name": "Plumbing"
},
How can I achive this in php. Is it possible to edit the contents of the main array? how can I add "items" after "category_name"
Regards..
$array = json_decode($yourJson);
$arrayLength = count($array);
$finalArray = [];
for ($i=0; $i < $arrayLength; $i+=2) {
$finalArray[] = $array[$i] + $array[$i + 1];
}
$backToJson = json_encode($finalArray);
Alternative to Mattijs's answer.
function get_first_property($object) {
$properties = array_keys(get_object_vars($object));
return reset($properties);
}
function object_merge($object1, $object2) {
return (object) array_merge((array) $object1, (array) $object2);
}
// loop through each of the array objects
$previous_first_property = null;
foreach ($array as $i => $object) {
$first_property = get_first_property($object);
// merge if the 1st property is "items", and the previous 1st was "category_id"
if ($first_property == "items" && $previous_first_property == "category_id") {
$array[$i - 1] = object_merge($array[$i - 1], $array[$i]);
unset($array[$i]);
}
$previous_first_property = $first_property;
}

How to create a combo chart (bar and line) with fusioncharts using data from MySQL database?

I found this code online to do basically everything I was looking for except they are not using data from a MySQL database where as I am. Here is their code:
{
"chart": {
"caption": "Inventory by Product Categories",
"bgcolor": "FFFFFF",
"plotgradientcolor": "",
"showalternatehgridcolor": "0",
"showplotborder": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"pyaxisname": "Cost of Inventory",
"syaxisname": "Units in Inventory",
"numberprefix": "$",
"labeldisplay": "STAGGER",
"slantlabels": "1",
"canvasborderalpha": "0",
"legendshadow": "0",
"legendborderalpha": "0",
"showborder": "0"
},
"categories": [
{
"category": [
{
"label": "Seafood",
"labelPadding": 0
},
{
"label": "Beverages",
"labelPadding": 12
},
{
"label": "Condiments",
"labelPadding": 0
},
{
"label": "Dairy Products",
"labelPadding": 12
},
{
"label": "Confections",
"labelPadding": 0
},
{
"label": "Meat/Poultry",
"labelPadding": 12
},
{
"label": "Grains/Cereals",
"labelPadding": 0
},
{
"label": "Produce",
"labelPadding": 12
}
]
}
],
"dataset": [
{
"seriesname": "Cost of Inventory",
"color": "008ee4",
"data": [
{
"value": "13510"
},
{
"value": "12480"
},
{
"value": "12024"
},
{
"value": "11271"
},
{
"value": "10392"
},
{
"value": "5729"
},
{
"value": "5594"
},
{
"value": "3549"
}
]
},
{
"seriesname": "Quantity",
"parentyaxis": "S",
"renderas": "Line",
"color": "f8bd19",
"data": [
{
"value": "701"
},
{
"value": "559"
},
{
"value": "507"
},
{
"value": "393"
},
{
"value": "386"
},
{
"value": "165"
},
{
"value": "258"
},
{
"value": "100"
}
]
}
]
}
This makes sense, but it's changing this JSON code to accept data from a database instead of hardcoding this that is difficult for me.
Here is the relevent part of my code:
<?php
$strQuery2 = "SELECT ScrapDate, SUM(Quantity) AS Quantity FROM Scrap WHERE Department = 'WE' GROUP BY ScrapDate ORDER BY ScrapDate";
// Execute the query, or else return the error message.
$result2 = $dbhandle->query($strQuery2) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
// If the query returns a valid response, prepare the JSON string
if ($result2) {
// The `$arrData` array holds the chart attributes and data
$arrData2 = array(
"chart" => array(
"caption" => "WE Last Week Scrap Quantity",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues"=> "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0",
"xAxisName"=> "Day",
"yAxisName"=> "Quantity"
)
);
$arrData2["data"] = array();
// Push the data into the array
while($row2 = mysqli_fetch_array($result2)) {
array_push($arrData2["data"], array(
"label" => $row2["ScrapDate"],
"value" => $row2["Quantity"],
// "link" => "deptDrillDown.php?Department=".$row["Department"]
)
);
}
$jsonEncodedData2 = json_encode($arrData2);
$columnChart2 = new FusionCharts("column2D", "chart2" , 600, 300, "chart-2", "json", $jsonEncodedData2);
// Render the chart
$columnChart->render();
$columnChart2->render();
// Close the database connection
$dbhandle->close();
}
?>
As of right now, I can get data from the MySQL database and put it into a graph very easily. Now I want to add 1 more dataset, how do I do this?
To dynamically update the chart, following methods turns very useful:
getJSONData: Fetches chart data in the JSON format.
setJSONData: Sets chart data in the JSON data format
A sample implementation is shown in the below snippet. The chart is initially rendered as the default column2d chart. Once the Add Area button is clicked, an area dataset gets visually updated. Similarly on clicking the Add Line button to add a line dataset. The Reset button restores to original column only visual.
var visitChart,
areaBtn = document.getElementById('area'),
lineBtn = document.getElementById('line'),
resetBtn = document.getElementById('reset');
FusionCharts.ready(function() {
visitChart = new FusionCharts({
type: 'mscombi2d',
renderAt: 'chart-container',
width: '500',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Actual Revenues, Targeted Revenues & Profits",
"subcaption": "Last year",
"xaxisname": "Month",
"yaxisname": "Amount (In USD)",
"numberprefix": "$",
"theme": "fint"
},
"categories": [{
"category": [{
"label": "Jan"
}, {
"label": "Feb"
}, {
"label": "Mar"
}, {
"label": "Apr"
}, {
"label": "May"
}, {
"label": "Jun"
}, {
"label": "Jul"
}, {
"label": "Aug"
}, {
"label": "Sep"
}, {
"label": "Oct"
}, {
"label": "Nov"
}, {
"label": "Dec"
}]
}],
"dataset": [{
"seriesname": "Actual Revenue",
"data": [{
"value": "16000"
}, {
"value": "20000"
}, {
"value": "18000"
}, {
"value": "19000"
}, {
"value": "15000"
}, {
"value": "21000"
}, {
"value": "16000"
}, {
"value": "20000"
}, {
"value": "17000"
}, {
"value": "25000"
}, {
"value": "19000"
}, {
"value": "23000"
}]
}]
}
}).render();
});
areaBtn.addEventListener('click', function() {
var dataset,
json = visitChart.getJSONData();
if (!(dataset = json.dataset)) {
dataset = json.dataset = [];
}
dataset.push({
"seriesname": "Profit",
"renderas": "area",
"showvalues": "0",
"data": [{
"value": "4000"
}, {
"value": "5000"
}, {
"value": "3000"
}, {
"value": "4000"
}, {
"value": "1000"
}, {
"value": "7000"
}, {
"value": "1000"
}, {
"value": "4000"
}, {
"value": "1000"
}, {
"value": "8000"
}, {
"value": "2000"
}, {
"value": "7000"
}]
});
visitChart.setJSONData(json);
areaBtn.disabled = true;
});
lineBtn.addEventListener('click', function() {
var dataset,
json = visitChart.getJSONData();
if (!(dataset = json.dataset)) {
dataset = json.dataset = [];
}
dataset.push({
"seriesname": "Projected Revenue",
"renderas": "line",
"showvalues": "0",
"data": [{
"value": "15000"
}, {
"value": "16000"
}, {
"value": "17000"
}, {
"value": "18000"
}, {
"value": "19000"
}, {
"value": "19000"
}, {
"value": "19000"
}, {
"value": "19000"
}, {
"value": "20000"
}, {
"value": "21000"
}, {
"value": "22000"
}, {
"value": "23000"
}]
});
visitChart.setJSONData(json);
lineBtn.disabled = true;
});
resetBtn.addEventListener('click', function() {
var dataset,
len,
json = visitChart.getJSONData();
if (!(dataset = json.dataset)) {
dataset = json.dataset = [];
}
if ((len = dataset.length) > 1) {
dataset.splice(1, len - 1);
}
visitChart.setJSONData(json);
areaBtn.disabled = false;
lineBtn.disabled = false;
});
<script src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"></script>
<button id='area'>Add Area</button>
<button id='line'>Add Line</button>
<button id='reset'>Reset</button>
<span id="chart-container">FusionCharts XT will load here!</span>
The data getting appended might be fetched from a database in a similar manner stated above.

Sort an JSON array based on array values

I have a JSON array like this
$countries = [
{
"id": "1",
"country_name": "Afghanistan",
},
{
"id": "2",
"country_name": "Albania",
},
{
"id": "3",
"country_name": "Algeria",
},
{
"id": "4",
"country_name": "American Samoa",
}
..
..
..
{
"id": "50",
"country_name": "Zimbabwe",
}
];
The following array contains, the list of countries that I need to sort to top
$top_countries = ['United States', 'United Kingdom', 'German'];
What is the best way to sort the above array as follows
$countries = [
{
"id": "30",
"country_name": "United States",
},
{
"id": "31",
"country_name": "United Kingdom",
},
{
"id": "20",
"country_name": "German",
},
{
"id": "1",
"country_name": "Afghanistan",
},
{
"id": "2",
"country_name": "Albania",
},
{
"id": "3",
"country_name": "Algeria",
},
{
"id": "4",
"country_name": "American Samoa",
}
..
..
..
{
"id": "50",
"country_name": "Zimbabwe",
}
];
// index "value" of country by name
$top = array_flip($top_countries);
usort($countries, function($a, $b) use ($top) {
// get "value" for each country, if it is in index
$aValue = isset($top[$a->country_name])?$top[$a->country_name]:-1;
$bValue = isset($top[$b->country_name])?$top[$b->country_name]:-1;
if ($aValue == $bValue) {
// preserve "original order", assuming they were ordered by id
return $a->id < $b->id ? -1 : 1;
}
return $aValue < $bValue ? 1:-1;
});

Parsing an array with PHP in a foreach loop

I want to parse an array with PHP's foreach loop to get the object names and values inside the 'ques' array.
[
{
"ques": [
{
"name": "comment",
"value": "comment me for the reason",
"sur_id": "1",
"user_id": "admin#gmail.com",
"pagename": "question_response"
},
{
"name": "check-box[]",
"value": "1"
},
{
"name": "radio",
"value": "radio 2"
},
{
"name": "yes",
"value": "no"
}
]
"ques":[
{
"name": "date",
"value": "2015-10-23"
},
{
"name": "select-deopdown",
"value": ""
},
{
"name": "true",
"value": "false"
},
{
"name": "number",
"value": "55"
}
]
}
]
I want to separate the value from the 'ques' array:
while ($fetch = mysql_fetch_array($query1)) {
$content = $fetch['CONTENT_VALUES'];
// print_r($content);
$content_value= mb_convert_encoding($content ,"UTF-8");
$datas = json_decode($content, true);
foreach($datas->ques as $values)
{
echo $values->value . "\n";
print_r($values);
}
$test[] = array('ques' => $datas ,'answer'=>$values);
}

php json_encode formatting results?

I have:
$all = array(
array('id'=>1, 'cat'=>'Main','type'=>'Name0'),
array('id'=>2, 'cat'=>'Main','type'=>'Name1'),
array('id'=>3, 'cat'=>'Main','type'=>'Name3'),
array('id'=>4, 'cat'=>'Main','type'=>'Name4'),
array('id'=>5, 'cat'=>'Secondary','type'=>'Name5'),
array('id'=>6, 'cat'=>'Secondary','type'=>'Name6'),
array('id'=>7, 'cat'=>'Secondary','type'=>'Name7'),
array('id'=>8, 'cat'=>'Other','type'=>'Name8'),
array('id'=>9, 'cat'=>'Other','type'=>'Name9'),
array('id'=>10, 'cat'=>'Other','type'=>'Name10'),
array('id'=>11, 'cat'=>'Other','type'=>'Name11'),
);
$result = array();
foreach($all as $array){
$result[$array['cat']][] = array('id'=>$array['id'],'type'=>$array['type']);
}
$json_type = json_encode($result);
Which returns:
{"Main":[{"id":"1","type":"name1"},{"id":"2","type":"name2"},{"id":"3","type":"name3"},{"id":"4","type":"name4"}],"Secondary":[{"id":"5","type":"name5"},{"id":"6","type":"name6"},{"id":"7","type":"name7"}],"Other":[{"id":"8","type":"name8"},{"id":"9","type":"name9"},{"id":"10","type":"name10"},{"id":"11","type":"name11"}]}
But I need it to return as:
[
{
"text": "Main",
"children": [
{
"id": "1",
"text": "name1"
},
{
"id": "2",
"text": "name2"
},
{
"id": "3",
"text": "name3"
},
{
"id": "4",
"text": "name4"
}
]
},
{
"text": "Secondary",
"children": [
{
"id": "5",
"text": "name5"
},
{
"id": "6",
"text": "name6"
},
{
"id": "7",
"text": "name7"
}
]
},
{
"text": "Other",
"children": [
{
"id": "8",
"text": "name8"
},
{
"id": "9",
"text": "name9"
},
{
"id": "10",
"text": "name10"
},
{
"id": "11",
"text": "name11"
}
]
}
]
To work with the select2 JQuery plugin, I'm working with.
the 'children' name doesn't matter, I think that's just a placeholder so it gets parsed correctly. I'm not sure how I would go about it, I've been trying str_replace() but even that hasn't been working out so great.
I would to it in 2 loops. The first one to group results by category, the 2nd one to format it to fit your needs:
$temp = array();
foreach($all as $array){
if (!isset($temp[$array['cat']])) {
$temp[$array['cat']] = array();
}
$temp[$array['cat']][] = array('id'=>$array['id'], 'type'=>$array['type']);
}
$result = array();
foreach ($temp as $key=>$value) {
$result[] = array('text'=>$key, 'children'=>$value);
}
echo json_encode($result);
This produces the following output:
[{"text":"Main","children":[{"id":1,"type":"Name0"},{"id":2,"type":"Name1"},{"id":3,"type":"Name3"},{"id":4,"type":"Name4"}]},{"text":"Secondary","children":[{"id":5,"type":"Name5"},{"id":6,"type":"Name6"},{"id":7,"type":"Name7"}]},{"text":"Other","children":[{"id":8,"type":"Name8"},{"id":9,"type":"Name9"},{"id":10,"type":"Name10"},{"id":11,"type":"Name11"}]}]

Categories