Include variable into array if not empty inside foreach - php

Include the name variable if the value is not empty inside the foreach. I tried this method code below but it include outside the array. I want to include within the array.
Sample Code:
$load_array = array();
foreach($stmt->fetchAll() as $row){
$load_array[] = array(
'name' => $row['name'],
'start_location' => array(
'address' => $row['start_address'],
'coords' => array (
'lat' => floatval($row['start_lat']),
'lng' => floatval($row['start_lng']),
),
),
);
if(!empty($row['shift_start'])) { $load_array['shift_start'] = $row['shift_start'];}
if(!empty($row['shift_end'])) { $load_array['shift_end'] = $row['shift_end'];}
}
return json_encode($load_array);
Output code above:
{
"0": {
"name": "Ramon Macger",
"start_location": {
"address": "76 Spilman Street GORSGOCH SA40 8ZB",
"coords": {
"lat": 42.45188,
"lng": -83.12829
}
}
},
"1": {
"name": "Roberto",
"start_location": {
"address": "76 Spilman Street GORSGOCH SA40 8ZB",
"coords": {
"lat": 42.45188,
"lng": -83.12829
}
}
},
"shift_start": "14:00",
"shift_end": "17:00"
}
The output should be like this:
{
"0": {
"name": "Ramon Macger",
"start_location": {
"address": "76 Spilman Street GORSGOCH SA40 8ZB",
"coords": {
"lat": 42.45188,
"lng": -83.12829
}
},
"shift_start": "14:00",
"shift_end": "17:00"
},
"1": {
"name": "Roberto",
"start_location": {
"address": "76 Spilman Street GORSGOCH SA40 8ZB",
"coords": {
"lat": 42.45188,
"lng": -83.12829
}
},
"shift_start": "14:00",
"shift_end": "17:00"
},
}
The shift_start and shift_end should be within the array not outside. My code is working in 1 array only and not on the foreach. However, it doesn't working within for each.

You need to add shift_start and shift_end values into the data array before you push it into $load_array. Something like this:
foreach($stmt->fetchAll() as $row){
$data = array(
'name' => $row['name'],
'start_location' => array(
'address' => $row['start_address'],
'coords' => array (
'lat' => floatval($row['start_lat']),
'lng' => floatval($row['start_lng']),
),
),
);
if(!empty($row['shift_start'])) {
$data['shift_start'] = $row['shift_start'];
}
if(!empty($row['shift_end'])) {
$data['shift_end'] = $row['shift_end'];
}
$load_array[] = $data;
}

Related

PHP convert CSV to JSON multi level

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 ?

PHP array to specified json structure

I need to get an JSON structure as following:
{
"emails": [
{
"sender": "shihas#abc.com",
"unread_count": 2,
"items": [
{
"id": "89",
"email": "shihas#abc.com",
"read": "0",
},
{
"id": "32",
"email": "shihas#abc.com",
"read": "0",
}
]
},
{
"sender": "marias123#gmail.com",
"unread_count": 0,
"items": [
{
"id": "2",
"email": "marias123#gmail.com",
"read": "1",
}
]
},
{
"sender": "gutar4320#hotmail.com",
"unread_count": 1,
"items": [
{
"id": "1",
"email": "gutar4320#hotmail.com",
"read": "0",
}
]
}
]
}
Array($hire_email):
In the below array I need to group all the details based on the email. And also count the no. of unread messages(i.e read = 0).
Array
(
[0] => Array
(
[id] => 89
[email] => shihas#abc.com
[read] => 0
)
[1] => Array
(
[id] => 32
[email] => shihas#abc.com
[read] => 0
)
[2] => Array
(
[id] => 2
[email] => marias123#gmail.com
[read] => 1
)
[3] => Array
(
[id] => 1
[email] => gutar4320#hotmail.com
[read] => 0
)
)
The following is the code snippet used for maintaining the JSON structure.
foreach($hire_email as $val) {
if($val['read']==0){ $count++; }else{ $count = 0;}
$hire_group_email[$val['email']]['sender'] = $val['email'];
$hire_group_email[$val['email']]['unread_count'] = $count;
$hire_group_email[$val['email']]['items'][] = $val;
}
$output["emails"][] = $hire_group_email;
echo json_encode($output);
This should do the trick.
$hire_email =array(
array(
"id" => "89",
"email" => "shihas#abc.com",
"read" => "0"
),
array
(
"id" => "32",
"email" => "shihas#abc.com",
"read" => "0"
),
array
(
"id" => "2",
"email" => "marias123#gmail.com",
"read" => "1"
),
array
(
"id" => "1",
"email" => "gutar4320#hotmail.com",
"read" => "0"
)
);
$tmp = array();
foreach($hire_email as $arg)
{
$tmp[$arg['email']][] = $arg;
}
$output = array();
foreach($tmp as $type => $labels)
{
$count = 0;
foreach ($labels as $value) {
if($value['read']==0){ $count++; }else{ $count = 0;}
}
$output[] = array(
'sender' => $type,
'unread_count' => $count,
'items' => $labels
);
}
echo json_encode($output);
Try doing it like this, using: array_sum and array_column, the rest is just picking out the first items values.
$array = json_decode($json, true)['emails'];
$result = [];
foreach($array as $val) {
$result[] = [
'id' => $val['items'][0]['id'],
'email' => $val['items'][0]['email'],
'read' => array_sum(array_column($val['items'], 'read'))
];
}
$output["emails"] = $result;
echo json_encode($output, JSON_PRETTY_PRINT);
Result:
{
"emails": [
{
"id": "89",
"email": "shihas#abc.com",
"read": 0
},
{
"id": "2",
"email": "marias123#gmail.com",
"read": 1
},
{
"id": "1",
"email": "gutar4320#hotmail.com",
"read": 0
}
]
}
https://3v4l.org/hi7qm
And if you want it as shown ;p (my mistake, misread it):
Loop over each item, then loop over the items and use that to build the output.
$array = json_decode($json, true)['emails'];
$result = [];
foreach($array as $val) {
foreach ($val['items'] as $item) {
$result[] = [
'id' => $item['id'],
'email' => $item['email'],
'read' => array_sum(array_column($val['items'], 'read'))
];
}
}
$output["emails"] = $result;
echo json_encode($output, JSON_PRETTY_PRINT);
Result:
{
"emails": [
{
"id": "89",
"email": "shihas#abc.com",
"read": 0
},
{
"id": "32",
"email": "shihas#abc.com",
"read": 0
},
{
"id": "2",
"email": "marias123#gmail.com",
"read": 1
},
{
"id": "1",
"email": "gutar4320#hotmail.com",
"read": 0
}
]
}
https://3v4l.org/eU95A

Add array elements in an array position

How can I add an array to array position:
Something like a:
<?php
$newArr = array('email' => array("id" => "5678", "token" => "fghjk"));
$arr = array(
"auth"=>
array(
'users'=>
array(
'id' =>"456yhjoiu",
'token' => "asdfghjkrtyui678"
)
)
);
somefunction($arr['auth'], $newArr);
I've tried array_push() but it added zero (0) before 'email' instead.~
I'm doing this to get a json output, something like this:
}
"auth": {
"users": {
"id": "456yhjoiu",
"token": "asdfghjkrtyui678"
},
"email": {
"id": "5678",
"token": "fghjk"
}
}
}
but I have this output:
{
"auth": {
"users": {
"id": "456yhjoiu",
"token": "asdfghjkrtyui678"
},
"0": {
"email": {
"id": "5678",
"token": "fghjk"
}
}
}
$data = ['auth' => array_merge($arr['auth'], $newArr)];
or old array notation <= PHP5.3
$data = array('auth' => array_merge($arr['auth'], $newArr));

Reformatting Json to geoJson in PHP (Laravel)

I have laravel outputting the following:
[
{
"id": 3,
"lat": "38.8978378",
"lon": "-77.0365123"
},
{
"id": 4,
"lat": "44.8",
"lon": "1.7"
},
{
"id": 22,
"lat": "37.59046",
"lon": "-122.348994"
}
]
i would like it to be the geoJson format:
{ "type": "FeatureCollection",
"features": [
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [lat, lon]},
"properties": {
"name": "value"
}
}
]
}
I know i need some sort of loop. But i'm not sure how to structure it in PHP. Any guidance would be greatly appreciated. Trying to build a map application that could have several thousand markers on a world view. I'm already thinking about clustering, but need to get past this basic step.
Thanks!
I modified the loop, the arrangement was a bit off. And turned it into a function if anyone is interested:
function geoJson ($locales)
{
$original_data = json_decode($locales, true);
$features = array();
foreach($original_data as $key => $value) {
$features[] = array(
'type' => 'Feature',
'geometry' => array('type' => 'Point', 'coordinates' => array((float)$value['lat'],(float)$value['lon'])),
'properties' => array('name' => $value['name'], 'id' => $value['id']),
);
};
$allfeatures = array('type' => 'FeatureCollection', 'features' => $features);
return json_encode($allfeatures, JSON_PRETTY_PRINT);
}
Just use json_decode() on the original values and rebuild/reconstruct a new one. Consider this example:
$original_json_string = '[{"id": 3,"lat": "38.8978378","lon": "-77.0365123"},{"id": 4,"lat": "44.8","lon": "1.7"},{"id": 22,"lat": "37.59046","lon": "-122.348994"}]';
$original_data = json_decode($original_json_string, true);
$coordinates = array();
foreach($original_data as $key => $value) {
$coordinates[] = array('lat' => $value['lat'], 'lon' => $value['lon']);
}
$new_data = array(
'type' => 'FeatureCollection',
'features' => array(
'type' => 'Feature',
'geometry' => array('type' => 'Point', 'coordinates' => $coordinates),
'properties' => array('name' => 'value'),
),
);
$final_data = json_encode($new_data, JSON_PRETTY_PRINT);
print_r($final_data);
$final_data should yield something like:
{
"type": "FeatureCollection",
"features": {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
{
"lat": "38.8978378",
"lon": "-77.0365123"
},
{
"lat": "44.8",
"lon": "1.7"
},
{
"lat": "37.59046",
"lon": "-122.348994"
}
]
},
"properties": {
"name": "value"
}
}
}

Array inside array

I want to put my data inside an array not on array within array,
Here's the result of Session::all
"imei": [
{
"imei_id": "3213",
"item_name": "item_name"
},
{
"imei_id": "3213",
"item_name": "Dustin Bailey"
}
]
This is the output of the array, after posting some data
"imei": [
[
{
"imei_id": "12312",
"item_name": "item_name"
},
{
"imei_id": "3213",
"item_name": "item_name"
},
{
"imei_id": "3123",
"item_name": "item_name"
}
]
]
Code on my Controller
foreach($imei as $imei_id => $imei_unit)
{
$items[] = array(
'imei_id' => $imei_unit,
'item_name' => $item_name,
);
}
Session::push('imei', $items);
do like this -
foreach($imei as $imei_id => $imei_unit)
{
$item = array(
'imei_id' => $imei_unit,
'item_name' => $item_name,
);
Session::push('imei', $item);
}
Try this:
foreach($imei as $imei_id => $imei_unit)
{
$items[]['imei_id'] = $imei_unit;
$items[]['item_name'] = $item_name;
}

Categories