How to parse JSON Array with different keys on the same level - php

I have Array and i need to get summ of quantity * price. But the array keys on the third level is different.
I use this PHP code but i only can take price & quantity for first item ['506-p1-8_p2-_p3-']
$quantity = $elements['1af7e792-bcff-4a6c-9bdb-dd5023b0251a']['items']['506-p1-8_p2-_p3-'][quantity];
$price = $elements['1af7e792-bcff-4a6c-9bdb-dd5023b0251a']['items']['506-p1-8_p2-_p3-'][price];
$summ = $price*$quantity;
How to parse all levels to get Summ = (price * quantity)
Thank to all who can help me
Array
(
[1af7e792-bcff-4a6c-9bdb-dd5023b0251a] => Array
(
[is_advance] => 1
[items] => Array
(
[506-p1-8_p2-_p3-] => Array
(
[hash] => 506-p1-8_p2-_p3-
[sku] => 501
[itemId] => 506
[quantity] => 6
[price] => 80.75
[currency] => UAH
[priceDesc] =>
[priceParams] => Array
(
[u0420u0430u0437u043cu0435u0440] => 8
)
[name] => qwerty
)
[498-p1-6_p2-_p3-] => Array
(
[hash] => 498-p1-6_p2-_p3-
[sku] => 498
[itemId] => 498
[quantity] => 5
[price] => 500
[currency] => UAH
[priceDesc] =>
[priceParams] => Array
(
[u0420u0430u0437u043cu0435u0440] => 6
)
[name] => qwerty
)
)
)
)

It's hard to tell how the array is generated in the first place. So just going off of the code you've posted, this should sum up the total for every item contained in the array.
$items = $elements['1af7e792-bcff-4a6c-9bdb-dd5023b0251a']['items'];
$sum = 0;
foreach($items as $item) {
$sum += $item['quantity'] * $item['price'];
}

In the sense of flexibility, you want your code as portable as possible. I assume your id isn't always going to be 1af7e792-bcff-4a6c-9bdb-dd5023b0251a, so you'll want to loop through the data that is returned.I don't know how you get the data, that's up to you.
So something like this, should gather the data you require and create an array:
$d = array();
foreach ($data as $id => $item) {
foreach ($item as $key => $values) {
$d[$id][$key]['sum'] = $values['price'] * $values['quantity'];
}
}
print_r($d);
Note: The above code is untested

Related

Taking out just one value from an array

I have an array which is
Array ( [0] => Array ( [picture] => 5a55ed8d8a5c8910913.jpeg
[id] => 1284
[price_range] => Rs 12000 - 9000
[name] => Brown Beauty Office Chair )
[1] => Array ( [picture] => 5a55eefeb9a8e255836.jpeg
[id] => 1285
[price_range] => Rs 8989 - 7000
[name] => Chang Series Office Chair (Grey)
)
)
Now I am fetching the value of id on clicking a remove button, the value I fetch is 1284.
I want to take out just [id]=> 1284 from the above array and then display it using a foreach loop. How I can delete just the [id]=> 1284 without disturbing the other id values and other element.
In the above array I would like to delete one particular id value say just the [id]=> 1284 and keep all other elements intact and as it is.
Any help is welcome.
Use array_search and array_column, to find by id and remove by unset method,
<?php
$array = [
["id"=>123,"desc"=>"test1"],
["id"=>456,"desc"=>"test2"],
["id"=>789,"desc"=>"test3"],
];
$id = 456;
$index = array_search($id, array_column($array, 'id'));
unset($array[$index]);
print_r($array);
?>
Live Demo
Array
(
[0] => Array
(
[id] => 123
[desc] => test1
)
[2] => Array
(
[id] => 789
[desc] => test3
)
)
Since you asked how to achieve it using foreach, I came up with this.
$array = Array (Array ( 'picture' => '5a55ed8d8a5c8910913.jpeg','id' => 1284,'price_range' => 'Rs 12000 - 9000', 'name' => 'Brown Beauty Office Chair'),
Array ( 'picture' => '5a55eefeb9a8e255836.jpeg','id' => 1285,'price_range' => 'Rs 8989 - 7000','name' => 'Chang Series Office Chair (Grey)')
);
foreach($array as $key => $val) {
$id = $array[$key]['id'];
if($id === 1284){
unset($array[$key]['id']);
}
}
print_r($array)
?>
You can also use this too:
<?php
$element_to_remove = 1284;
$i = 0;
foreach($array as $this_arr){
$index = array_search($element_to_remove, $this_arr);
//unset($this_arr[$index]); this formate does not remove element from array
//but below works fine
if(isset($array[$i][$index])){
unset($array[$i][$index]);
}
}
print_r($array);
?>

Sum array on key - possible or is the array not structured in a good way?

Have built the following array based on an accounting file and want to create sums from the [trans] subarray for all accounts based on the amount. Looked into array_column but have a feeling the array is not built correctly or in an efficient way for this? Any thoughts/suggestions much appreciated.
//Clarification
Hi! Many thanks. I was probably a bit unclear. For the total population of [trans] I want to sum the amount where the account is the same. So the array above would generate:
[1930] = -150.47-431.63
[5912] = 150.47
etc
[#VER] => Array
(
[A1] => Array
(
[verdatum] => 20150107
[vertext] => GOOGLE
[trans] => Array
(
[0] => Array
(
[account] => 1930
[amount] => -150.47
)
[1] => Array
(
[account] => 5912
[amount] => 150.47
)
[2] => Array
(
[account] => 2645
[amount] => 37.62
)
[3] => Array
(
[account] => 2614
[amount] => -37.62
)
)
)
[A2] => Array
(
[verdatum] => 20150118
[vertext] => Post
[trans] => Array
(
[0] => Array
(
[account] => 1930
[amount] => -431.63
)
[1] => Array
(
[account] => 5710
[amount] => 345.30
)
[2] => Array
(
[account] => 2641
[amount] => 86.33
)
)
)
)
Its simply a foreach loop to acheive your expected sum of amount
$temp = array();
$new = array();
foreach($arr as $key=>$value){
foreach($value["trans"] as $key2=>$value2){
if(in_array($value2["account"], $temp)){
$new[$value2["account"]] += $value2["amount"];
}else {
$new[$value2["account"]] = $value2["amount"];
$temp[] = $value2["account"];
}
}
}
print_r($new);
Live demo : https://eval.in/857342
Output will be
Array
(
[1930] => -582.1
[5912] => 150.47
[2645] => 37.62
[2614] => -37.62
[5710] => 345.3
[2641] => 86.33
)
$grand_total = 0;
array_walk($my_array['#VER'],function (&$ver) use (&$grand_total){
$ver['total_amount'] = 0;
foreach($ver['trans'] as $trans){
$ver['total_amount'] += $trans['amount'];
}
$grand_total += $ver['total_amount'];
});
So, simply loop through your "VER" then loop again on each trans. As simple as that. I've used both array_walk and foreach techniques, mainly to show you the two ways. You could prefer use two foreach, or two array_walk, it would work.
This script adds to a $grand_total variable, and also store the total of all transactions into each VER entry.
Modified:
$grand_total = 0;
array_walk($urarr['#VER'],function (&$ver) use (&$grand_total){
foreach($ver['trans'] as $trans){
if ($trans['amount'] < 0){
$neg += abs($trans['amount']);
}else{
$pos += abs($trans['amount']);
}
}
$diff = ($pos < $neg) ? "-".($neg - $pos) : ($pos - $neg);
$grand_total += $diff;
});
print $grand_total;

Multiple array data in php and get the SUM

I am using Codeigniter and I have a function like this .
function total_income(){
$data['total_income'] = $this->mod_products->total_income();
echo"<pre>";
print_r($data['total_income']);
}
The above code return an array like this.
Array
(
[0] => stdClass Object
(
[sub_product_price] => 1000
[quantity] => 1
)
[1] => stdClass Object
(
[sub_product_price] => 1000
[quantity] => 1
)
[2] => stdClass Object
(
[sub_product_price] => 50
[quantity] => 15
)
[3] => stdClass Object
(
[sub_product_price] => 500
[quantity] => 5
)
)
Now I want to get the [sub_product_price] and multiply that value with [quantity] .Then I want to get the array_sum. I don't have an idea how to do that. Could some one help me It would be grate ,
Cheers!! Rob
$sum = 0;
foreach ($array as $obj) {
$sum += ($obj->quantity * $obj->sub_product_price);
}
Add the all values after multiplication in an empty array and use array_sum() to get the final value.
$temp = array();
foreach($data['total_income'] as $in)
{
$temp[] = $in->sub_product_price * $in->quantity;
}
$total = array_sum($temp);
Explanation:
array_sum() returns the sum of all the values of an array.
Example,
$array = array(4,5,6);
echo array_sum($array); // 15

PHP Replacing Array Value

Im creating an array of products, each with an ID and score:
$savedProducts = array( 'product' => array("product_id" => $product_id,"product_score" => $score));
I want to be able to update the score by using the product_id as identifier.
I've tried:
foreach($savedProducts as $key => $val)
{
if ($val == $property_id )
{
$savedProducts[$key] = $score;
break;
}
}
Which keeps adding a new array item, rather than updating the original.
I think the issue is that my initial array setup then doesn't match the edited one.
Initial array:
Array
(
[product] => Array
(
[product_id] => 125026
[product_score] => 5
)
)
After trying to update score:
Array
(
[0] => Array
(
[product] => Array
(
[product_id] => 125026
[product_score] => 4
)
)
[1] => Array
(
[0] => Array
(
[product] => Array
(
[product_id] => 125026
[product_score] => 4
)
)
)
)
So it keeps addding elements, rather than updating the existing.
with PHP 5.5 use:
$savedProducts = array_column($savedProducts, NULL, 'product_id');
then you can access your product with:
$savedProducts[$product_id]
Please try this
foreach($savedProducts as $key => $val)
{
if($val['product_id'] == $property_id)
{
$savedProperties[$key]['product_score'] = $score;
break;
}
}

Loop logic help needed - Can't compare correctly

I have the following table:
And I use this function to get data from it:
function get_cart_by($player_id)
{
global $db;
$sql = 'SELECT DISTINCT(item_id) FROM ' . PCP_MARKET_CART . '
WHERE player_id = ' . (int) $player_id;
$result = $db->sql_query($sql);
$rowset = $db->sql_fetchrowseT($result);
$db->sql_freeresult($result);
$cart = array();
foreach ($rowset as $item)
{
$cart[] = $item['item_id'];
}
return $cart;
}
The result looks like this:
Array
(
[0] => 16
[1] => 17
[2] => 49
[3] => 48
[4] => 18
[5] => 19
[6] => 51
)
Now I have an array that lists all my products from another table without looking at the player_id. I want to use the array demonstrated above and add a custom class to the items that do not use the player_id, like show which items the user already has on cart.
The other array that lists all the products looks like this:
Array
(
[0] => Array
(
[item_id] => 16
[parent_id] => 11
[cat_position] => 0
[item_position] => 1
[item_type] => product
[item_title] => Custom Business
[item_description] => Some description
[item_price] => 9.99
[item_units] => 500
[item_preview] => http://i.imgur.com/3eCpMMm.png
[times_sold] => 0
[daopay_url] => http://i.imgur.com/QA7bBfJ.jpg
[public] => 1
[time] => 1384709635
)
[1] => Array
(
[item_id] => 17
[parent_id] => 11
[cat_position] => 0
[item_position] => 1
[item_type] => product
[item_title] => Custom Business
[item_description] => Some description
[item_price] => 9.99
[item_units] => 500
[item_preview] => http://i.imgur.com/3eCpMMm.png
[times_sold] => 0
[daopay_url] => http://i.imgur.com/QA7bBfJ.jpg
[public] => 1
[time] => 1384709635
)
[2] => Array
(
[item_id] => 49
[parent_id] => 11
[cat_position] => 0
[item_position] => 1
[item_type] => product
[item_title] => Custom Business
[item_description] => Some description
[item_price] => 9.99
[item_units] => 500
[item_preview] => http://i.imgur.com/3eCpMMm.png
[times_sold] => 0
[daopay_url] => http://i.imgur.com/QA7bBfJ.jpg
[public] => 1
[time] => 1384709635
)
)
Now based on the first array, I want to mark the same item IDs on the second arrays and show that they are different (on cart).
I have tried quite a lot and for some reason, I managed to mark only item_id 16 and 17, the rest are not getting "marked" for some reason.
This is the code I used:
$cartar = $market->get_cart_by($user->data['player_id']);
$cartln = sizeof($cartar) - 1;
// Fetch items of the selected category
$items = $market->fetch_cat_items($cat_id); // Equivalent to the array above
$index = 0;
print_r($items);
foreach ($items as $item)
{
$name = $item['item_name'];
if ($cartln >= $index)
{
if ($cartar[$index] == $item['item_id'])
$name .= $cartar[$index];
}
echo $name;
$index++;
}
I tried to make the example explain my case the best way possible. So, when I echo out $name it only outputs thename16 and thename17 (those two), but it doesn't continue to 49 and so on.
Please be aware that the array with all the products in it is quite large, I made it shorter for demonstration purposes only.
Were am I failing in my code? Why are only the first two items getting "marked"? I'm quite in a hurry right now, once I get back from a meeting I'll try to explain my issue further.
i don't know if i understood correctly but maybe you want to do it like this:
foreach ($items as $item) {
$name = $item['item_name'];
if(in_array($item['item_id'],$cartar)) {
$name .= $item['item_id'];
}
echo $name;
}
used in_array() to check if the item_id exists somewhere in $cartar. No matter on which position in array.

Categories