I have an array structure that is stored in Session
edit : the number of item_id's is not definite. It maybe 1-3 items on one transaction and 2-20 items on the next.
"items": [{
"item_id": "1",
"item_quantity": "151"
}, {
"item_id": "2",
"item_quantity": "54"
}, {
"item_id": "2",
"item_quantity": "23"
}, {
"item_id": "3",
"item_quantity": "3"
}, {
"item_id": "3",
"item_quantity": "3"
}]
What I'm trying to achieve is to add up all item_quantity which has the same item_id
"items": [{
"item_id": "1",
"item_quantity": "151"
}, {
"item_id": "2",
"item_quantity": "77"
}, {
"item_id": "3",
"item_quantity": "6"
}]
This is what I have tried so far, but I'm not getting the desired result
Controller
public function Save() {
if (Input::has('addItem')) {
if (Session::has('items')) {
Session::push('items', [
'item_id' => Input::get('item_id'),
'item_quantity' => Input::get('item_quantity')
]);
$array = Session::get('items');
foreach($array as $key => $value) {
foreach($value as $item_id => $item_quantity) {
$total = array();
$id = $value['item_id'];
$quantity = $value['item_quantity'];
if (!isset($total[$id])) {
$total[$id] = 0;
}
$total[$id] += $quantity;
echo $total[$id];
}
} else {
Session::put('items', [
0 => [
'item_id' => Input::get('item_id'),
'item_quantity' => Input::get('item_quantity')
]
]);
}
$data = Session::all();
//return $data;
$item = Item::lists('item_name', 'id');
return View::make('test')->with('data', $data)->with('items', $item);
}
You're on the right track. See comments in the code.
public function Save() {
if (Input::has('addItem')) {
if (Session::has('items')) {
Session::push('items', [
'item_id' => Input::get('item_id'),
'item_quantity' => Input::get('item_quantity')
]);
$array = Session::get('items');
$total = array(); //move outside foreach loop because we don't want to reset it
foreach ($array as $key => $value) {
$id = $value['item_id'];
$quantity = $value['item_quantity'];
if (!isset($total[$id])) {
$total[$id] = 0;
}
$total[$id] += $quantity;
echo $total[$id];
}
//now convert our associative array from array(actual_item_id => actual_item_quantity,....)
//into array(array('item_id' => actual_item_id, 'item_quantity' => actual_item_quantity), ....)
$items = array();
foreach($total as $item_id => $item_quantity) {
$items[] = array(
'item_id' => $item_id,
'item_quantity' => $item_quantity
);
}
Session::put('items', $items);
} else {
Session::put('items', [
0 => [
'item_id' => Input::get('item_id'),
'item_quantity' => Input::get('item_quantity')
]
]);
}
$data = Session::all();
//return $data;
$item = Item::lists('item_name', 'id');
return View::make('test')->with('data', $data)->with('items', $item);
}
}
You could choose to create a new array, and from that, sum the values from the old. You could do something like this. Consider this example:
// dummy data
$raw = '{"items": [{ "item_id": "1", "item_quantity": "151"}, { "item_id": "2", "item_quantity": "54"}, { "item_id": "2", "item_quantity": "23"}, { "item_id": "3", "item_quantity": "3"}, { "item_id": "3", "item_quantity": "3"}]}';
$values = json_decode($raw); // for sample data's sake
$values = reset($values); // get first level 'items'
$new_values = array();
foreach($values as $key => $value) {
if(!isset($new_values[$value->item_id])) $new_values[$value->item_id] = new stdClass(); // initialize new object
if(!isset($new_values[$value->item_id]->item_quantity)) $new_values[$value->item_id]->item_quantity = 0; // initialize default value
$new_values[$value->item_id]->item_id = $value->item_id; // append new item id
$new_values[$value->item_id]->item_quantity += $value->item_quantity; // sum values
}
echo '<pre>';
print_r($new_values);
echo '</pre>';
Sample Output:
Array
(
[1] => stdClass Object
(
[item_quantity] => 151
[item_id] => 1
)
[2] => stdClass Object
(
[item_quantity] => 77
[item_id] => 2
)
[3] => stdClass Object
(
[item_quantity] => 6
[item_id] => 3
)
)
Sample Fiddle
Related
I need to create a json with this format:
{
"reservs": [
{
"ResId": "58",
"time": "2020-05-15 19:41:50",
"boxEntering": null,
"boxClosing": null,
"active": "1",
"UserId": "29",
"BoxId": "4",
"boxPlace": null,
"box": {
"id": "4",
"Nom": "Hortillonages",
"Lat": "49.8953",
"Lng": "2.31034",
"place": "0",
"placeMax": "9"
}
}
]
}
in entries, a $header who check the user token(not use for my problem)
$table the table returned from PDO::FETCHASSOC from sql SELECT request
My php code:
function generateJson($table, headerChecker $header){
$final = array();
foreach ($table as $item) {
$box = array(
"id" => $item["id"],
"Nom" => $item["Nom"],
"Lat" => $item["Lat"],
"Lng" => $item["Lng"],
"place" => $item["place"],
"placeMax" => $item["placeMax"]
);
$reserv = array(
"ResId" => $item["ResId"],
"time" => $item["time"],
"boxEntering" => $item["boxEntering"],
"boxClosing" => $item["boxClosing"],
"active" => $item["active"],
"UserId" => $item["UserId"],
"BoxId" => $item["BoxId"],
"boxPlace" => $item["boxPlace"],
);
$reserv["box"] = $box;
array_merge($final,$reserv);
}
$arr = array("reservs" => $table);
$header->tokenJson($arr);
echo json_encode($arr);
}
I have this result
{"reservs": [
{
"ResId": "58",
"time": "2020-05-15 19:41:50",
"boxEntering": null,
"boxClosing": null,
"active": "1",
"UserId": "29",
"BoxId": "4",
"boxPlace": null,
"id": "4",
"Nom": "Hortillonages",
"Lat": "49.8953",
"Lng": "2.31034",
"place": "0",
"placeMax": "9",
"QRID": "",
"boxToken": ""
}]
}
I think the Json format eror is in the array_merge function.
What add array function can I use to not remove the Box object
Your problem is that you are not assigning the return of array_merge and using the wrong variable $table. Just dynamically append to $final:
foreach ($table as $item) {
// this all appears good
//
$reserv["box"] = $box;
$final[] = $reserv; // append to $final
}
$arr = array("reservs" => $final); // use $final
$header->tokenJson($arr);
echo json_encode($arr);
Merge the new $reserv into $final and assign it to $final, then use $final.
Try this one
function generateJson($table, headerChecker $header){
$final = array();
foreach ($table as $item) {
$box = array(
"id" => $item["id"],
"Nom" => $item["Nom"],
"Lat" => $item["Lat"],
"Lng" => $item["Lng"],
"place" => $item["place"],
"placeMax" => $item["placeMax"]
);
$reserv = array(
"ResId" => $item["ResId"],
"time" => $item["time"],
"boxEntering" => $item["boxEntering"],
"boxClosing" => $item["boxClosing"],
"active" => $item["active"],
"UserId" => $item["UserId"],
"BoxId" => $item["BoxId"],
"boxPlace" => $item["boxPlace"],
);
$reserv["box"] = $box;
$final[] = $reserv;
}
$arr = array("reservs" => $final);
$header->tokenJson($arr);
echo json_encode($arr);
}
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
I have one array. In that array categoryName means we have to make multidimensional array, otherwise we have to make normal array. i tried but i am not able to make my expected JSON Format.
print_r($search_result);
Array
(
[0] => Array
(
[productId] => 1
[categoryName] => Shoes
[brandName] => Adidas
)
[1] => Array
(
[productId] => 2
[categoryName] => Jeans
[brandName] => LEVIS
)
[2] => Array
(
[productId] => 3
[categoryName] => Jeans
[brandName] => LEVIS
)
)
using this array i want to make like this JSON Format
{
"status": "Success",
"data": [
{
"categoryName": "Shoes",
"products": [
{
"productId": "1",
"brandName": "Adidas"
}
]
},
{
"categoryName": "Jeans",
"products": [
{
"productId": "2",
"brandName": "LEVIS"
},
{
"productId": "2",
"brandName": "LEVIS"
}
]
}
]
}
for getting above my expected results i tried like this but is not happening. i am getting json format
protected function getCategorywiseProducts(){
if($this->get_request_method() != "GET"){
$this->response('',406);
}
$sql = "SELECT productId,categoryName,brandName FROM product";
$mainArray = array();
$search_result = $this->GetJoinRecord($sql);
$tasks = array();
foreach ($search_result as $key => $value) {
$tasks[$value['categoryName']][] = $value;
}
if(count($tasks)>0) {
$response_array['status']='success';
$response_array['categories'][]=$tasks;
$this->response($this->json($response_array), 200);
} else {
$response_array['status']='fail';
$response_array['message']='Record not found.';
$response_array['data']='';
$this->response($this->json($response_array), 204);
}
}
I am getting like this JSON format
{
"status": "success",
"categories": [
{
"Shoes": [
{
"productId": "1",
"categoryName": "Shoes",
"brandName": "Adidas"
}
],
"Jeans": [
{
"productId": "2",
"categoryName": "Jeans",
"brandName": "LEVIS"
},
{
"productId": "3",
"categoryName": "Jeans",
"brandName": "LEVIS"
}
]
}
]
}
Try modifying the function like this:
protected function getCategorywiseProducts(){
if($this->get_request_method() != "GET"){
$this->response('',406);
}
$sql = "SELECT productId,categoryName,brandName FROM product";
$mainArray = array();
$search_result = $this->GetJoinRecord($sql);
$tasks = array();
foreach ($search_result as $key => $value) {
$tasks['categoryName'][$key] = $value['categoryName'];
$tasks['products']['productId'][$key] = $value['productId'];
$tasks['products']['brandName'][$key] = $value['brandName'];
}
if(count($tasks)>0) {
$response_array['status']='success';
$response_array['categories'][]=$tasks;
$this->response($this->json($response_array), 200);
} else {
$response_array['status']='fail';
$response_array['message']='Record not found.';
$response_array['data']='';
$this->response($this->json($response_array), 204);
}
}
As you can see, I've only changed the foreach loop.
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;
}
I am trying to convert following table data into nested array using PHP. I am almost done but stuck at one point.
id name parent
1 Apparel
2 Appliances
46 Apparel 1
47 Child Apparel 46
49 Child Apparel 2 47
Using this code
$cats = array(); // from database
$refs = array();
$rcats = array();
foreach ($cats as $cat) {
$thisref = &$refs[$cat['id']];
$thisref['id'] = $cat['id'];
$thisref['name'] = $cat['name'];
$thisref['leaf'] = "true";
if (!$cat['parent']) {
$rcats[$cat['id']] = &$thisref;
} else {
unset($refs[$cat['parent']]['leaf']);
$refs[$cat['parent']]['items'][$cat['id']] = &$thisref;
}
}
print_r(json_encode($rcats));
This results into following JSON.
{
"1": {
"id": "1",
"name": "Apparel",
"items": {
"46": {
"id": "46",
"name": "Apparel",
"items": {
"47": {
"id": "47",
"name": "Child Apparel",
"items": {
"49": {
"id": "49",
"name": "Child Apparel 2",
"leaf": "true"
}
}
}
}
}
}
},
"2": {
"id": "2",
"name": "Appliances",
"leaf": "true"
}
}
Where as I want the JSON like
[
{
"id": "1",
"name": "Apparel",
"items": [
{
"id": "46",
"name": "Apparel",
"items": [
{
"id": "47",
"name": "Child Apparel",
"items": [
{
"id": "49",
"name": "Child Apparel 2",
"leaf": "true"
}
]
}
]
}
]
},
{
"id": "2",
"name": "Appliances",
"leaf": "true"
}
]
Am i wrong? :p
$cats = array(); // From Database, but i use this
$cats = array(
array(
'id' => 1,
'name' => 'Jakarta',
'parent' => NULL
),
array(
'id' => 2,
'name' => 'Bandung',
'parent' => 1
),
array(
'id' => 3,
'name' => 'Surabaya',
'parent' => 1
),
array(
'id' => 4,
'name' => 'Bali',
'parent' => NULL
),
array(
'id' => 5,
'name' => 'Batam',
'parent' => NULL
),
);
$refs = array();
$rcats = array();
foreach ($cats as $cat) {
$thisref = &$refs[$cat['id']];
$thisref['id'] = $cat['id'];
$thisref['name'] = $cat['name'];
$thisref['leaf'] = "true";
if (!$cat['parent']) {
$rcats[] = &$thisref;
}
else {
unset($refs[$cat['parent']]['leaf']);
$refs[$cat['parent']]['items'][] = &$thisref;
}
}
/*
// IF YOU NEED CHANGE TO OBJECT
$rcats = (object)$rcats;
if(isset($rcats->items)){
$rcats->items = (object)$rcats->items;
}
*/
header('Content-type: application/json');
print_r(json_encode($rcats));
Here I'm assuming you are storing your final results in $refs
print_r(json_encode(array_values($rcats)));
If you want to take out all the indexes, in your for loop, do [] instead of the id:
if (!$cat['parent']) {
$rcats[] = &$thisref;
} else {
unset($refs[$cat['parent']]['leaf']);
$refs[$cat['parent']]['items'][] = &$thisref;
}
A quick example I throw:
<?php
$a = array('1' => array('a' => 3), '2' => array('b' => 4));
echo json_encode($a) . "\n";
echo json_encode(array_values($a)) . "\n";
Outputs:
{"1":{"a":3},"2":{"b":4}}
[{"a":3},{"b":4}]