Array inside array - php

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;
}

Related

Reformat json in a correct way

I have this php code as I am trying to execute a particular function in my php project, I code the implementation correct but I ran into a small problem.
<?php echo '<script type="text/javascript">';
$data = array(
'base' => 'USD',
'alter' => 'ETH',
'data' => array()
);
foreach ($cryptos as $row) {
$sy = $row["symbol"];
$data['data'][] = array(
"$sy" => [
"rate" => 1.552000000000000,
"min" => 1.0077600000000000,
"max" => 10.077600000000000,
"code" => $row["symbol"],
"dp" => 8
],
);
}
print_r("var fxCur = " . json_encode($data));
Running the code above I got this result below, That's the expected result but I want to omit [] between data
{
"base":"USD",
"alter":"ETH",
"data":[
{
"BTC":{
"rate": 1.552000000000000,
"min": 1.0077600000000000,
"max": 10.077600000000000,
"code":"BTC",
"dp":8
}
},
{
"ETH":{
"rate": 1.552000000000000,
"min": 1.0077600000000000,
"max": 10.077600000000000,
"code":"ETH",
"dp":8
}
}
]
}
But actually I wanted this result
{
"base":"USD",
"alter":"ETH",
"data":{
"BTC":{
"rate": 1.552000000000000,
"min": 1.0077600000000000,
"max": 10.077600000000000,
"code":"BTC",
"dp":8
},
"ETH":{
"rate": 1.552000000000000,
"min": 1.0077600000000000,
"max": 10.077600000000000,
"code":"ETH",
"dp":8
},
}
}
You're telling it to construct the data structure that way.
$data['data'][] = array(
"$sy" => [
...
]
);
That line says "append an element to $data['data'] at the next integer index and set it equal to the array e.g. [ "BTC" => [ ... ]]
I think what you want is:
$data['data'][$sy] = [
"rate" => 1.552000000000000,
"min" => 1.0077600000000000,
"max" => 10.077600000000000,
"code" => $row["symbol"],
"dp" => 8
];

How to modify json key

I need some help to reorder the data in a json file.
I have these few lines :
foreach($rows as $row) {
$data[] = array(
"$row[0]" => array(
"name" => "$row[1]",
"value" => "$row[2]",
"conso" => "$row[3]",
"ml" => "$row[4]"
)
);
}
$data = json_encode($data, JSON_FORCE_OBJECT);
This function allows me to obtain something like this :
This function allows me to obtain something like this :
{
"0": {
"tata": {
"name": "name_01",
"value": "value_01",
"conso": "conso_01",
"ml": "ml_01"
}
},
"1": {
"toto": {
"name": "name_02",
"value": "value_02",
"conso": "conso_02",
"ml": "ml_02"
}
}
}
I would like something like that :
{
"tata": {
"name": "name_01",
"value": "value_01",
"conso": "conso_01",
"ml": "ml_01"
},
"toto": {
"name": "name_02",
"value": "value_02",
"conso": "conso_02",
"ml": "ml_02"
}
}
Get rid of a layer of array, and specify the key you want. You also don't need to quote all the variables like that.
foreach($rows as $row) {
$data[$row[0]] = array(
"name" => $row[1],
"value" => $row[2],
"conso" => $row[3],
"ml" => $row[4]
);
}
$data = json_encode($data, JSON_FORCE_OBJECT);

Include variable into array if not empty inside foreach

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;
}

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));

Add array values of same array keys in session

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

Categories