I have a CSV file like this
first_name,last_name,phone
Joseph,Dean,2025550194
Elbert,Valdez,2025550148
Using this csv-to-json.php from GitHub I get output like this
[{
"first_name": "Joseph",
"last_name": "Dean",
"phone": "2025550194",
"id": 0
}, {
"first_name": "Elbert",
"last_name": "Valdez",
"phone": "2025550148",
"id": 1
}]
This is almost what I want - however instead of
"phone": "2025550194"
I need
"phone": [{
"type": "phone",
"number": "2025550194"
}]
How do I correct this?
If you get the JSON string, then you would of course first convert it to an array with:
$arr = json_decode($json, true);
But probably you already have the array. You then apply this loop to it:
foreach($arr as &$row) {
if (isset($row['phone'])) { // only when there is a phone number:
$row['phone'] = [[ "type" => "phone", "number" => $row['phone'] ]];
}
}
See it run on eval.in.
You can change the csv-to-json.php code with following and you got the output that you want :-
Option 1 :-
// Bring it all together
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
if ($j == 'phone') {
$newArray[$j] = array('type' => $j, 'number' => $d);
} else {
$newArray[$j] = $d;
}
}
Option 2 :-
$json_response = [{
"first_name": "Joseph",
"last_name": "Dean",
"phone": "2025550194",
"id": 0
}, {
"first_name": "Elbert",
"last_name": "Valdez",
"phone": "2025550148",
"id": 1
}];
$result = json_decode($json_response);
$final_result = array();
foreach ($result as $row) {
$row['phone'] = array('type' => 'phone', 'number' => $row['phone']);
$final_result[] = $row;
}
echo json_encode($final_result);
It may help you.
Related
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 have a CSV data looks like this :
ps.csv
id|firstName|lastName|address|extId|extName
001|Kapil|Parames|address01|AA01|AA
002|David|Vuitton|address01|AA02|AA
002|David|Vuitton|address02|BB02|BB
003|Jean|Paul|address01|AA03|AA
And i need an output JSON to look like this :
[
{
"id": "001",
"firstName": "Kapil",
"lastName": "Parames",
"address": [{
"address": "address01"
}],
"ext": [{
"extId": "AA01",
"extName": "AA"
}]
},
{
"id": "002",
"firstName": "David",
"lastName": "Vuitton",
"address": [{
"address": "address01"
},
{
"address": "address02"
}
],
"ext": [{
"extId": "AA02",
"extName": "AA"
},
{
"extId": "BB02",
"extName": "BB"
}
]
},
{
"id": "003",
"firstName": "Jean",
"lastName": "Paul",
"address": [{
"address": "address01"
}],
"ext": [{
"extId": "AA03",
"extName": "AA"
}]
}
]
I can convert it to JSON. But the problem is i would like to add "address" and "extId", "extName" into multi level array if the person already exists in the list.
So following PHP code is working for me :
$csv = file('ps.csv');
$csvArray = [];
foreach ($csv as $line) {
$csvArray[] = str_getcsv($line, '|', ',');
}
$jsonArray = [];
for ($i = 1; $i < count($csvArray); $i++) {
$found = -1;
for ($j = 0; $j < count($jsonArray); $j++) {
if (in_array($csvArray[$i][0], $jsonArray[$j])) {
$found = $j;
}
}
if ($found < 0) {
$jsonArray[] = array(
'id' => $csvArray[$i][0],
'firstName' => $csvArray[$i][1],
'lastName' => $csvArray[$i][2],
'address' => array(
[
'address' => $csvArray[$i][3]
]
),
'ext' => array(
[
'extId' => $csvArray[$i][4],
'extName' => $csvArray[$i][5]
]
)
);
} else {
$addressArray = array(
'address' => $csvArray[$i][3]
);
$extArray = array(
'extId' => $csvArray[$i][4],
'extName' => $csvArray[$i][5]
);
array_push($jsonArray[$found]['address'], $addressArray);
array_push($jsonArray[$found]['ext'], $extArray);
}
}
echo '<pre>';
echo json_encode($jsonArray, JSON_PRETTY_PRINT);
echo '</pre>';
Is that correct or is there any other way to do ?
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;
}
}
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);
}
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.