PHP - fetch json data - php

I have problem with this script...
My script has return this:
{
"categories": {
"cid": "1",
"name": "Pierwsza pomoc"
}
}{
"categories": {
"cid": "2",
"name": "Poradniki"
}
}{
"categories": {
"cid": "3",
"name": "Klany"
}
}{
"categories": {
"cid": "4",
"name": "Eventy, imprezy"
}
}{
"categories": {
"cid": "5",
"name": "Rozm\u00f3wki"
}
}{
"categories": {
"cid": "6",
"name": "Quest, solucje"
}
}{
"categories": {
"cid": "7",
"name": "Off topic"
}
}
But i want to this
[
'categories': {
'cid': 1,
'name': 'test',
'cid': 2,
'name': 'asdsad',
'cid': 3,
'name': 'asdasd'
}
]
Code used to create the data is
if($query->rowCount() > 0){
foreach($query as $row){
$Forum->writeJSON(array('categories' => array( 'cid' => $row['id'], 'name' => $row['name'] )));
}
}
class Forum {
public function writeJSON($array){
echo json_encode($array, JSON_PRETTY_PRINT);
}
}
$Forum = new Forum;

Well, this structure is not possible. You cannot store two or more elements with exactly same key in same object. However maybe you simply want this output:
[ 'categories' : { 1: {category_id:1, name:'test'}, 2: {category_id:2, name:'test'} } ]
It is simple, for example, you can use something like this to form that array:
<?php
//fetch data into categories variable
$output = array();
$output['categories'] = array();
foreach ($category as $category){
$output['categories'][] = array('category_id' => $category['id'], 'name' => $category['name']);
}
$output = json_encode($output);
?>
PS: Please use the correct variable names in your code, this is just an example using fictitious variable names

You need to change your foreach loop code
if($query->rowCount() > 0){
foreach($query as $row){
$cat_array[$row['id']] = array('cid'=>$row['id'],'name'=>$row['name']);
}
$json_array[] = array('categories'=>$cat_array);
$Forum->writeJSON($json_array);
}

Related

merge all arrays with same title [duplicate]

This question already has answers here:
How to group subarrays by a column value?
(20 answers)
PHP - Group Array by its Sub Array Value (Indexed Array)
(1 answer)
Closed 6 months ago.
i have this array in php json.
i have made it to sort array by first Characther.
but now i'm stuck on how to merge the data under the same title.
my response now is.
[
{
"title": "A",
"data": {
"id": "317",
"name": "Aesethetica"
}
},
{
"title": "A",
"data": {
"id": "318",
"name": "Astonos"
}
},
{
"title": "B",
"data": {
"id": "320",
"name": "Bourjois"
}
},
{
"title": "B",
"data": {
"id": "321",
"name": "Bioderma"
}
}
]
i need to merge all data under each same title.
something like this:
[
{
"title": "A",
"data": [
{
"id": "317",
"name": "Aesethetica"
},
{
"id": "318",
"name": "Astonos"
}
]
},
{
"title": "B",
"data": [
{
"id": "320",
"name": "Bourjois"
},
{
"id": "321",
"name": "Bioderma"
}
]
}
]
kindly help.
Thanks
i got this now:
i made this update.. but still not the needed result.
this is my php code...
$result = [];
foreach ($data as $item) {
$firstLetter = substr($item['name'], 0, 1);
$result[] = [
'title' => $firstLetter = ctype_alnum($firstLetter) ? $firstLetter : '#',
'data' => $item
];
}
foreach ($result as $key => $item) {
$arr[$item['title']][$key] = $item;
}
and this is the result.
{
"A": [
{
"title": "A",
"data": {
"brand_id": "312",
"brand_name": "Adidsa"
}
},
{
"title": "A",
"data": {
"id": "314",
"name": "Adio"
}
},
still can't find make the needed response..
This is not perfomance optimized, but shows a simple solution.
Collect all data grouped by title, then reformat the array to your expected result.
$array = json_decode($json, true);
$collect = [];
foreach($array as $item) {
$collect[$item['title']][] = $item['data'];
}
ksort($collect);
$titles = [];
foreach($collect as $title => $data) {
$names = array_column($data, 'name');
array_multisort($names, SORT_ASC, SORT_STRING, $data);
$titles[] = ['title' => $title, 'data' => $data];
}
echo json_encode($titles, JSON_PRETTY_PRINT); results in
[
{
"title": "A",
"data": [
{
"id": "317",
"name": "Aesethetica"
},
{
"id": "318",
"name": "Astonos"
}
]
},
{
"title": "B",
"data": [
{
"id": "321",
"name": "Bioderma"
},
{
"id": "320",
"name": "Bourjois"
}
]
}
]

Laravel : get data array and loop with For

Hi I'am trying to get data Array and looping with For. So I have array called 'color' and I want loop the Array with For. But I have some trouble in the result. I've been tried change the array and in foreach but I got no idea how to get result like what I want.
The Result :
"data": [
{
"title": "get data users",
"function_name": "selectDataUser",
"function_drop": "selectDataUser",
"type_of_chart": "Pie",
"embed": null,
"created_at": "2019-06-15 03:26:09.000",
"updated_at": null,
"data_chart": [
{
"name": "Administrator",
"total": "100",
"color": "0xFF888888" //color cannot be the same
},
{
"name": "Staff",
"total": "100",
"color": "0xFF888888" //the color must be different
},
{
"name": "Super Administrator",
"total": "1",
"color": "0xFF888888" //this is not result what I want.
}
],
}
]
I want response like this:
"data": [
{
"title": "get data users",
"function_name": "selectDataUser",
"function_drop": "selectDataUser",
"type_of_chart": "Pie",
"embed": null,
"created_at": "2019-06-15 03:26:09.000",
"updated_at": null,
"data_chart": [
{
"name": "Administrator",
"total": "100",
"color": "0xFF000000" //all this color different
},
{
"name": "Staff",
"total": "100",
"color": "0xFF444444" //the color different
},
{
"name": "Super Administrator",
"total": "1",
"color": "0xFF888888" //this is result what I want.
}
],
}
]
This my code :
public function index(Request $request)
{
try {
$query = $this->dashboard->with('rolesDashboard','userDashboard')
->orderBy('id')
->get();
$data=[];
foreach ($query as $key) {
$data_chart = DB::select($key->function_name); //call store procedure from SQL Server
$color = array(
"0xFF000000" ,
"0xFF444444" ,
"0xFF888888" ,
"0xFFCCCCCC",
"0xFFFFFFFF",
"0xFFFF0000" ,
"0xFF00FF00" ,
); // this is array color
for ($i=0; $i < count($data_chart) ; $i++) {
$set = $color[$i]; //Get data array color
}
foreach($data_chart as $row){
$row->color = $set;
}
$data[] = [
'title' => $key->title,
'function_name' => $key->function_name,
'created_at' => $key->created_at,
'updated_at' => $key->updated_at,
'data_chart' => $data_chart, //return data_chart and color
];
}
return response()->default(200, trans('messages.success.get-data'),$data);
} catch (Exception $e) {
return response()->default(400, $e->getMessage());
}
}
$set is array, cannot be assigned as a string. My advice is changing below code:
for ($i=0; $i < count($data_chart) ; $i++) {
$set = $color[$i]; //Get data array color
}
foreach($data_chart as $row){
$row->color = $set;
}
to
$i=0;
foreach($data_chart as $row){
$row->color = $color[$i];
$i++;
}
but if your $data_chart count is more than $color count it will return error, for better handling use code below:
$i=0;
foreach($data_chart as $row){
if(isset($color[$i])){
$row->color = $color[$i];
$i++; }
else{
$i=0;
}
}

json data formating wrapped inside a var

I have a json data generated with the following php code
$index = array();
foreach($rows as $row)
{
$row['data'] []= (object) [];
$index[$row['cat_id']] = $row;
}
// build the tree
foreach($index as $id => &$row)
{
if ($id === 0) continue;
$parent = $row['parent'];
$index [$parent]['children'][] = &$row;
}
unset($row);
// obtain root node
$index = $index[0]['children'][0];
$json_data = json_encode($index, JSON_PRETTY_PRINT);
which produces the following json
{
"cat_id": "1",
"id": "RT",
"name": "root",
"parent": "0",
"url": "www.test.com",
"data": [
{}
],
"children": [
{
"cat_id": "4",
"id": "CI.001",
"name": "Test2",
"parent": "2",
"url": "www.test.com",
"data": [
{}
]
}
what i want is the output to be like this
var something = [{
"cat_id": "1",
"id": "RT",
"name": "root",
"parent": "0",
"url": "www.test.com",
"data": [
{}
],
"children": [
{
"cat_id": "4",
"id": "CI.001",
"name": "Test2",
"parent": "2",
"url": "www.test.com",
"data": [
{}
]
}];
I have looked through the web with some suggesting that it is not json but php array i'm new to json. How can I solve this ?
Here is is my solution at the moment.
ob_start();
echo "var javascript_array = [". $json_data . "];\n";
$content = ob_get_contents();
file_put_contents('../core/json/tree.js', $content);
Any suggestions and improvements will be appreciated.

Fetch particular data from duplicated record in PHP

I just wanted to know is there a possibility to get specific columns from duplicated row in PHP-MySQL connection and use them to the existing data in JSON?
/...db connection etc.
if ($statement->execute())
{
$response["lecturer"] = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$lecturer = array();
$lecturer["id"] = $row["lecturerid"];
$lecturer["image"] = $row["l_image"];
$lecturer["degree"] = $row["degree"];
$lecturer["name"] = $row["l_name"];
$lecturer["surname"] = $row["surname"];
$lecturer["field"] = array();
$lecturer["field"]["fieldid"] = $row["fieldid"];
$lecturer["field"]["name"] = $row["f_name"];
array_push($response["lecturer"], $lecturer);
}
}
/... json_encode etc.
So, there can be a situation, where one lecturer has 2 different fields, and I'm getting something like this:
{
"lecturer": [
{
"id": 1,
"image": "http://...",
"degree": "PhD",
"name": "John",
"surname": "Doe",
"field": {
"fieldid": 13,
"name": "field1"
}
},
{
"id": 1,
"image": "http://...",
"degree": "PhD",
"name": "John",
"surname": "Doe",
"field": {
"fieldid": 14,
"name": "field2"
}
},
Instead of that, I would like to get JSON:
{
"lecturer": [
{
"id": 1,
"image": "http://...",
"degree": "PhD",
"name": "John",
"surname": "Doe",
"field": {
"fieldid": 13,
"name": "field1",
"fieldid": 14,
"name": "field2"
}
},
In the MySQL database there are two tables: lecturer, and field, but also lecturer_field table, where I have relation between lecturerid and fieldid.
As i was pointed out, it's impossible to declare similar named field in json object:
"field": {
"fieldid": 13,
"name": "field1",
"fieldid": 14,
"name": "field2"
}
Valid case is
"field": [{
"fieldid": 13,
"name": "field1",
},
{
"fieldid": 14,
"name": "field2"
}]
You can do that in this way:
if ($statement->execute())
{
$indexedLecturers = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$lid = $row["lecturerid"];
if (isset($indexedLecturers[$lid])) {
array_push($indexedLecturers[$lid]["field"], array(
"fieldid" => $row["fieldid"],
"name" => $row["f_name"],
));
} else {
$lecturer = array();
$lecturer["id"] = $lid;
$lecturer["image"] = $row["l_image"];
$lecturer["degree"] = $row["degree"];
$lecturer["name"] = $row["l_name"];
$lecturer["surname"] = $row["surname"];
$lecturer["field"] = array();
array_push($lecturer["field"], array(
"fieldid" => $row["fieldid"],
"name" => $row["f_name"],
));
$indexedLecturers[$lid] = $lecturer;
}
}
$response['lecturer'] = array_values($indexedLecturers);
}

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