mySql outputs this:
As you can see row 3 and 4 has duplicates so I want to merge these duplicates when I output my Json. To be exact I want my json to be like this:
[
{
"name": "The Crane Bar",
"lat": "53.2692",
"lng": "-9.06151",
"events": [
{
"name": "Traditional music session",
"info": null
}
]
},
{
"name": "Taaffes Bar",
"lat": "53.2725",
"lng": "-9.05321",
"events": [
{
"name": "6 Nations, Italy VS Ireland",
"info": null
}
]
},
{
"name": "a house",
"lat": "37.4401",
"lng": "-122.143",
"events": [
{
"name": "Party at Palo Alto",
"info": "Some info about the party"
},
{
"name": "2gdfgdf",
"info": "2gdfgdfgdf"
}
]
}
]
You know use one one location_name, lat and lng and have nested the event_name and post_content (as info here).
Thanks!
Based on your comment, you want the results to be nested, so when you generate the JSON, iterate over the rows and build a nested result list in PHP:
$result = array();
$item = null;
for ($i = 0; $i < count($rows); ++$i) {
$row = $rows[$i];
if ($item === null) {
$item = array('location' => $row['location'], 'events' => array());
}
$item['events'][] = array('name' => $row['event_name']);
if ($i == count($rows) - 1 || $row['location'] != $rows[$i + 1]['location']) {
$result[] = $item;
$item = null;
}
}
echo json_encode($result); // JSON-encoded data
Now each location will have an events list with one or more entries.
Related
I have a array of objects in PHP like:
[
{
"id": 99961,
"candidate": {
"data": {
"id": 125275,
"firstName": "Jose",
"lastName": "Zayas"
}
},
"dateAdded": 1667995574207
},
{
"id": 99960,
"candidate": {
"data": {
"id": 125274,
"firstName": "CHRISTIAN",
"lastName": "NEILS"
}
},
"dateAdded": 1667986477133
},
{
"id": 99959,
"candidate": {
"data": {
"id": 125273,
"firstName": "Jose",
"lastName": "Zayas"
}
},
"dateAdded": 1667985600420
},
{
"id": 99958,
"candidate": {
"data": {
"id": 125275,
"firstName": "Jose",
"lastName": "Zayas"
}
},
"dateAdded": 1667985600420
},
]
I want to find duplicates based on same candidate firstName and lastName but different candidate id's.
I have tried multiple methods like array_search, array_column, array_filter etc but nothing giving desired result.
Output should be array of candidate.data.id that are different but with same firstName and lastName.
Can anyone guide me in building the algorithm?
Group on a key which is composed of the candidate's first name and last name and push the respective id as a child of that group using the id as the key and the value -- this ensures uniqueness within the group.
Then filter out the candidates that only occur once and re-index the qualifying subsets.
Code: (Demo)
$grouped = [];
foreach ($array as $row) {
$compositeKey = "{$row['candidate']['data']['firstName']} {$row['candidate']['data']['lastName']}";
$grouped[$compositeKey][$row['candidate']['data']['id']] = $row['candidate']['data']['id'];
}
$result = [];
foreach ($grouped as $id => $group) {
if (count($group) > 1) {
$result[$id] = array_values($group);
}
}
var_export($result);
Output:
array (
'Jose Zayas' =>
array (
0 => 125275,
1 => 125273,
),
)
Or with one loop, collect all unique ids per group then push all keys into the result array if more than 1 total in the group. (Demo)
$duplicated = [];
foreach ($array as $row) {
$compositeKey = "{$row['candidate']['data']['firstName']} {$row['candidate']['data']['lastName']}";
$id = $row['candidate']['data']['id'];
$grouped[$compositeKey][$id] = '';
if (count($grouped[$compositeKey]) > 1) {
$duplicated[$compositeKey] = array_keys($grouped[$compositeKey]);
}
}
var_export($duplicated);
You need to set iteration for to pick key data (firstName and lastName) for buffer. After it, you can check key from buffer data for to find exists users. :
<?php
$arr = <<<JSON
[
{
"id": 99959,
"candidate": {
"data": {
"id": 125273,
"firstName": "Jose",
"lastName": "Zayas"
}
},
"dateAdded": 1667985600420
},
{
"id": 99961,
"candidate": {
"data": {
"id": 125275,
"firstName": "Jose",
"lastName": "Zayas"
}
},
"dateAdded": 1667995574207
},
{
"id": 99960,
"candidate": {
"data": {
"id": 125274,
"firstName": "CHRISTIAN",
"lastName": "NEILS"
}
},
"dateAdded": 1667986477133
},
{
"id": 99958,
"candidate": {
"data": {
"id": 125275,
"firstName": "Jose",
"lastName": "Zayas"
}
},
"dateAdded": 1667985600420
}
]
JSON;
$candidatePersonality = $exits = [];
$json = json_decode($arr,true);
array_walk($json,function($item,$key) use(&$candidatePersonality,&$exits){
$userKey = $item['candidate']['data']['firstName'].' '.$item['candidate']['data']['lastName'];
if(!isset($candidatePersonality[$userKey]) || (isset($candidatePersonality[$userKey]) && !in_array( $item['candidate']['data']['id'],$candidatePersonality[$userKey]))){
$candidatePersonality[$userKey][] = $item['candidate']['data']['id'];
if(count($candidatePersonality[$userKey])> 1){
$exits[$userKey] = $candidatePersonality[$userKey];
}
}
});
echo '<pre>';
print_r($exits);
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"
}
]
}
]
I tried to parse a JSON using PHP from url. I need a list of item that have no children - means children field should be empty array and parent_id shouldn't be 0 - means not be parents.
JSON:
{
"body": {
"data": [
{
"id": 1,
"name": "car",
"parent_id": "0",
"children": [
{
"id": 2,
"name": "bmw",
"parent_id": "1",
"children": [
{
"id": 4,
"name": "bmw i8",
"parent_id": "2",
"children": []
}
]
},
{
"id": 3,
"name": "mustang",
"parent_id": "1",
"children": []
}
]
},
{
"id": 5,
"name": "clothes",
"parent_id": "0",
"children": []
},
{
"id": 6,
"name": "mobile",
"parent_id": "0",
"children": [
{
"id": 7,
"name": "apple",
"parent_id": "6",
"children": [
{
"id": 9,
"name": "Iphone 12 pro",
"parent_id": "7",
"children": []
},
{
"id": 10,
"name": "Iphone 11",
"parent_id": "7",
"children": []
}
]
},
{
"id": 8,
"name": "Xiaomi",
"parent_id": "6",
"children": []
}
]
}
]
}
}
Output Expected:
[4,3,9,10,8]
This is my php code that i tried and doesn't work.
$CategoryUrl = file_get_contents(self::CATEGORY_URL,true);
$array = json_decode($CategoryUrl,true);
$list = array();
foreach( $array['body']['data'] as $value ){
if (($value['parent_id'] != 0) && empty($value['children'])) {
foreach( $value['children'] as $val ){
$list[] = $val;
}
}
}
print_r($list);
It is indeed a little tricky to keep track of parent ID values and children call using array_walk_recursive as it jumps directly to its children. However, this can be still accomplished with your own recursive version like below. Keep checking with parent_id and children count. If both constraints satisfy, add them to $result, else keep calling children recursively.
<?php
$str = '{"body":{"data":[{"id":1,"name":"car","parent_id":"0","children":[{"id":2,"name":"bmw","parent_id":"1","children":[{"id":4,"name":"bmw i8","parent_id":"2","children":[]}]},{"id":3,"name":"mustang","parent_id":"1","children":[]}]},{"id":5,"name":"clothes","parent_id":"0","children":[]},{"id":6,"name":"mobile","parent_id":"0","children":[{"id":7,"name":"apple","parent_id":"6","children":[{"id":9,"name":"Iphone 12 pro","parent_id":"7","children":[]},{"id":10,"name":"Iphone 11","parent_id":"7","children":[]}]},{"id":8,"name":"Xiaomi","parent_id":"6","children":[]}]}]}}';
$data = json_decode($str,true);
$result = [];
function walkRecursive($data,&$result){
foreach($data as $entry){
if($entry['parent_id'] != 0 && count($entry['children']) == 0){
$result[] = $entry['id'];
}else{
walkRecursive($entry['children'],$result);
}
}
}
walkRecursive($data['body']['data'],$result);
print_r($result);
We can solve this problem by function call recursive algorithm,
hope it clear for you
$CategoryUrl = file_get_contents(self::CATEGORY_URL,true);
$array = json_decode($CategoryUrl, true);
$items = $array['body']['data'];
$list = [];
findParentIds(items, $list);
// doSomething
print_r($list);
/**
* passe by ref (list)
* #param array $children
* #param $list
*/
function findParentIds(array $children, & $list)
{
foreach ($children as $child) {
// use case 1: has no children and parent_id is 0 , just continue
if (empty($child['children']) && $child['parent_id'] == "0") {
continue;
}
// use case 2: has no children and parent_id is 0 , it's parent item
if (empty($child['children']) && $child['parent_id'] != "0") {
array_push($list, $child['id']);
}
// has children and parent_id is not 0 , recall function to treat use case 1 and 2 ..
findParentIds($child['children'], $list);
}
}
I have 2 JSON files that I would like to parse, and merge into one object and output as a single JSON.
but I can't figure out how to do and get the correct result, every time i try always get a single result like this :
[
{
"Title": "Some title for your blog",
"url": "\/post.php?id=1",
"image": "https:\/\/example.com\/images\/small\/1.jpg"
}
]
what i need is to call all the 2 json data to 1 json like this one :
[
{
"Title": "second title for your blog",
"url": "\/post.php?id=2",
"image": "https:\/\/example.com\/images\/small\/2.jpg"
}
{
"Title": "second title for your blog",
"url": "\/post.php?id=2",
"image": "https:\/\/example.com\/images\/small\/2.jpg"
}
{
"Title": "third title for your blog",
"url": "\/post.php?id=3",
"image": "https:\/\/example.com\/images\/small\/3.jpg"
}
and so on... till the end of loop
]
Here is my code :
$requestUrl="http://example.com/json1.php";
$requestUrl1="http://example.com/json2.php";
$data=file_get_contents($requestUrl);
$data1=file_get_contents($requestUrl1);
$array1 = json_decode($data);
$array2 = json_decode($data1);
$wholedata= [];
$i=0;
foreach ($array1 as $array1) {
$item['Title'] = $array1->title;
$item['url'] = $array1->url;
}
foreach ($array2 as $array2) {
$item['image'] = $array2->image;
}
$wholedata[] = $item;
$i++;
$json = json_encode($wholedata, JSON_PRETTY_PRINT);
header('Access-Control-Allow-Origin: *');
header('Content-type: Application/JSON');
echo $json;
Here's the json data :
Json 1
[
{
"title": "first title for your blog",
"url": "/post.php?id=1"
},
{
"title": "Second title for your blog",
"url": "/post.php?id=2"
},
{
"title": "Third title for your blog",
"url": "/post.php?id=3"
},
{
"title": "Fourth title for your blog",
"url": "/post.php?id=4"
},
{
"title": "Fifth title for your blog",
"url": "/post.php?id=5"
}
]
Json 2 :
[
{
"image": "https://example.com/images/small/1.jpg"
},
{
"image": "https://example.com/images/small/2.jpg"
},
{
"image": "https://example.com/images/small/3.jpg"
},
{
"image": "https://example.com/images/small/4.jpg"
},
{
"image": "https://example.com/images/small/5.jpg"
}
]
To do this with objects (as you are currently using), you can use the index of the first array to get the data from the second array. Then build the output in one go with the components from both objects and add them to your output...
$array1 = json_decode($data);
$array2 = json_decode($data1);
$wholedata= [];
foreach ($array1 as $key => $itemData) {
$wholedata[] = ['Title' => $itemData->title,
'url' => $itemData->url,
'image' => $array2[$key]->image];
}
$json = json_encode($wholedata, JSON_PRETTY_PRINT);
Try deocoding the json in an array and then merge them. Check out the official PHP documentation
array-merge - Merges two array
json_decode - Converts json into an array
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;
}
}