Max Value of multidimensional array - php

I have this Array
Array
(
[2014-08-14] => Array
(
[18:00:00] => Array
(
[6] => Array
(
[price] => 15.36
[avail_clean] => 5
[avail_noclean] => 6
)
[7] => Array
(
[price] => 17.35
[avail_clean] => 2
[avail_noclean] => 3
)
)
[19:00:00] => Array
(
[6] => Array
(
[price] => 15.36
[avail_clean] => 5
[avail_noclean] => 6
)
[7] => Array
(
[price] => 17.35
[avail_clean] => 2
[avail_noclean] => 3
)
)
)
)
How can I get the following for 6 & 7 seperately:
- Sum of price
- max of avail_clean
- max of avail_noclean
I got that far for the price:
foreach ($bookable as $date=>$key) {
foreach ($key as $time=>$key2) {
foreach($key2 as $room=>$key3){
foreach($key3 as $price=>$key4){
if($price == "price"){
if(isset($sumRoom[$room]['total'])){
$sumRoom[$room]['total'] += $key4;
}else{
$sumRoom[$room]['total'] = $key4;
}
}
}
}
}
}
Gives me this
Array(
[6] => Array
(
[total] => 30,72
)
[7] => Array
(
[total] => 34,7
)
)
But what about the max(), where should I put that?

foreach ($bookable as $date=>$times) {
foreach ($times as $time=>$rooms) {
foreach($rooms as $room=>$options){ $sumRoom[$room]['total'] = 0;
foreach($options as $option=>$value){
if($option == "price"){
$sumRoom[$room]['total'] += $value;
}
if($option == "avail_clean"){
$avail_clean[$room][] = $value;
}
if($option == "avail_noclean"){
$avail_noclean[$room][] = $value;
}
}
$sumRoom[$room]['avail_clean_max'] = max($avail_clean[$room]);
$sumRoom[$room]['avail_noclean'] = max($avail_noclean[$room]);
}
}
}
I've edited my answer.. I've merged all in one array i.e. $sumRoom

Related

Sum of value based on the key PHP

We have and array like below in PHP, and want to create a new array in the new array there should be the unique key and the value from the same key should be added.
Array
(
[0] => Array
(
[58] => 32.00
)
)
Array
(
[0] => Array
(
[58] => 34.00
)
)
Array
(
[0] => Array
(
[57] => 26.00
)
)
Array
(
[0] => Array
(
[57] => 27.00
)
)
Array
(
[0] => Array
(
[56] => 16.00
)
)
Array
(
[0] => Array
(
[56] => 17.00
)
)
We want to create new array with the help of the above array.
The value of same key should be added.
The output of new array should be like below.
Array
(
[58] => 66
[57] => 53
[56] => 33
)
code is below
The output of minmaxarray is
Array
(
[0] => Array
(
[min] => 35.00
[max] => 50.00
[price] => 26.00
)
[1] => Array
(
[min] => 50.00
[max] => 80.00
[price] => 29.00
)
[2] => Array
(
[min] => 80.00
[max] => 100.00
[price] => 32.00
)
[3] => Array
(
[min] => 100.00
[max] => 150.00
[price] => 34.00
)
[4] => Array
(
[min] => 150.00
[max] => 180.99
[price] => 36.00
)
)
$shippingPrice = array();
foreach ($minmaxarray as $key => $value) {
if($price > $value['min'] && $price < $value['max'])
{
if($value['price'])
{
$shippingPrice[][$smethodid] = $value['price'];
break;
}
}
}
echo '<pre>'; print_r ($shippingPrice);
Thanks
If your array structure is always the same like you have posted, then this code will work for you:
$example_array = array(
array( '0' => 32.00 ),
array( '2' => 32.00 ),
array( '2' => 32.00 )
);
$new_array = array();
// loop through every item in nested foreach
foreach( $example_array as $value ) {
foreach( $value as $key => $number ) {
// if the array key not exist, calculate with 0, otherwise calculate with the actual value
$new_array[$key] = isset($new_array[$key]) ? $new_array[$key] + $number : 0 + $number;
}
}
print_r( $new_array );
// prints Array ( [0] => 32 [2] => 64 )
Code example for your arrays:
$shippingPrice = array();
// loop through every item in nested foreach
foreach( $minmaxarray as $value ) {
foreach( $value as $key => $number ) {
// if the array key not exist, calculate with 0, otherwise calculate with the actual value
$shippingPrice[$key] = isset($shippingPrice[$key]) ? $shippingPrice[$key] + $number : 0 + $number;
}
}
echo '<pre>';
print_r( $shippingPrice );
You can try this code
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach($array as $key=> $value){
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
You call this function by your array then function will return your expected array.
array_flatten($array);
You can use array_walk_recursive instead of 2 foreach loop
array_walk_recursive($arr, function($v,$k) use (&$r){
$r[$k] = isset($r[$k]) ? ($r[$k]+$v) : $v;
});
Working demo :- https://3v4l.org/MMDEv

concat array values, if contains duplicates - php

This is my array. And i need to concat array values if duplicate exists.
Array
(
[0] => Array
(
[id] => 3
[location_id] => 2
[location_name] => 1st Floor
[type] => 1
)
[1] => Array
(
[id] => 6
[location_id] => 2
[location_name] => 1st Floor
[type] => 1
)
[2] => Array
(
[id] => 7
[location_id] => 1
[location_name] => Ground Floor
[type] => 1
)
)
And below is my code, which doesn't concat on unique values.
$conct= array();
foreach ($myArray as $array)
{
foreach ($array as $key => $value)
{
if ( ! isset($merged[$key]))
{
$conct[$key] = $value;
}
else
{
$conct[$key] .= ",".$value;
}
}
}
This is giving me.
Array
(
[0] => Array
(
[id] => 3,6,7
[location_id] => 2,2,1
[location_name] => 1st Floor,1st Floor,Ground Floor
[type] => 1,1,1
)
)
And i need to concat the values based on unique location_id and location_name.
My result array should be.
Array
(
[0] => Array
(
[id] => 3,6
[location_id] => 2,2
[location_name] => 1st Floor,1st Floor
[type] => 1,1
)
[1] => Array
(
[id] => 7
[location_id] => 1
[location_name] => Ground Floor
[type] => 1
)
)
How to achieve this?
Try this..
<?php
$new_values = array();
$values = array(
array('id'=> 1, 'location_id' => 2, 'location_name' => '1st Floor','type'=>1),
array('id'=> 6, 'location_id' => 2, 'location_name' => '1st Floor','type'=>1),
array('id'=> 7, 'location_id' => 1, 'location_name' => 'Gound Floor','type'=>1),
);
foreach($values as $value) {
if(isset($new_values[$value['location_id']])) {
$temp = $new_values[$value['location_id']];
$temp['id'] .= ',' . $value['id'];
$temp['location_id'] .= ',' . $value['location_id'];
$temp['location_name'] .= ',' . $value['location_name'];
$temp['type'] .= ',' . $value['type'];
$new_values[$value['location_id']] = $temp;
} else {
$new_values[$value['location_id']] = $value;
}
}
$new_values = array_values($new_values);
print_r($new_values);
?>
Output:Array ( [0] => Array ( [id] => 1,6 [location_id] => 2,2 [location_name] => 1st Floor,1st Floor [type] => 1,1 ) [1] => Array ( [id] => 7 [location_id] => 1 [location_name] => Gound Floor [type] => 1 ) )
$input = array(array('id'=>3,'location_id'=>2,'location_name'=>'1st Floor','type'=>1),
array('id'=>6,'location_id'=>2,'location_name'=>'1st Floor','type'=>1),
array('id'=>7,'location_id'=>1,'location_name'=>'Ground Floor','type'=>1)
);
$conct = array();
foreach($input as $k => $_input) {
foreach($_input as $key => $value) {
if(isset($conct[$key])) {
if(check_duplicate($duplicate,$input[$k])) {
$conct[$key] .= ",".$value;
} else {
$new[$key] = $value;
}
}
else
{
$conct[$key] = $value;
if($key=='location_id'||$key=='location_name')
$duplicate[$key] = $value;
}
}
}
function check_duplicate($duplicate=array(),$input=array()) {
foreach($duplicate as $dupe) {
if($dupe===$input['location_id'] || $dupe === $input['location_name'] )
return true;
else
return false;
}
}
echo "<pre>"; print_r($conct);
echo "<pre>"; print_r($new);

How to loop over associative array using foreach loop construct in following scenairo?

I've an array titled $rebate_by_product:
Array
(
[op] => preview
[id] =>
[form_submitted] => yes
[company_id] => 46
[1] => Array
(
[pack] => 10
[quantity] => 20
[volume] => 30
[units] => 9
[amount] => 40
[rebate_start_date] => 2014-05-01
[rebate_expiry_date] => 2014-05-05
[applicable_states] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[rebate_total_count] => 5000
[products] => Array
(
[1] => 9
[2] => 10
)
)
[2] => Array
(
[pack] => 50
[quantity] => 60
[volume] => 70
[units] => 10
[amount] => 80
[rebate_start_date] => 2014-05-06
[rebate_expiry_date] => 2014-05-10
[applicable_states] => Array
(
[0] => 14
[1] => 15
[2] => 16
)
[rebate_total_count] => 10000
[products] => Array
(
[1] => 11
[2] => 8
)
)
[3] => Array
(
[pack] => 100
[quantity] => 200
[volume] => 300
[units] => 7
[amount] => 400
[rebate_start_date] => 2014-05-21
[rebate_expiry_date] => 2014-05-30
[applicable_states] => Array
(
[0] => 26
[1] => 33
[2] => 42
)
[rebate_total_count] => 9999
[products] => Array
(
[1] => 9
[2] => 8
)
)
[multiselect] => 42
)
You can observe from above array that it has few elements which are not array but it has three such elements which are themselves array and even few of its data elements are also arrays so how to loop over this kind of array using foreach loop?
If you just want to print each one the just use foreach loop. Consider this example:
$product_keys = array(); // edited
// loop them, if its an array, loop inside it again
foreach($rebate_by_product as $index => $element) {
if(is_array($element)) {
foreach($element as $key => $value) {
if(is_array($value)) {
// EDITED
if($key == 'products') {
$product_keys = array_merge($product_keys, $value);
}
$value = implode(',', $value);
echo "$key => $value <br/>";
} else {
echo "$key => $value <br/>";
}
}
} else {
echo "$index => $element <br/>";
}
}
// if product items has duplicates check here (edited)
if(count($product_keys) != count(array_unique($product_keys))) {
echo "<script>alert('This array has duplicate products');</script>";
} else {
echo "<script>alert('Products are ok');</script>";
}
Or if you want, you cant just use iterators on this one:
$recursive = new RecursiveIteratorIterator(new RecursiveArrayIterator($rebate_by_product));
foreach($recursive as $key => $value) {
echo "$key => $value <br/>";
}
I'd propose you're use a recursive approach to bring all the entries of the array on the same level and then print this array:
function loopArray($inputVal,$inputKey = "") {
if(is_array($inputVal)) {
$output = array();
foreach($inputVal as $key => $value) {
$output = array_merge($output,loopArray($value,$key));
}
return $output;
} else {
return array($inputKey => $inputVal);
}
}
// Just for presenting:
$yourArray = array(
"1" => "1",
array(
"2.1" => "2.1",
array(
"2.2.1" => "2.2.1"
)
),
"3" => "3",
array(
"4.1" => "4.1"
)
);
$newArray = loopArray($yourArray);
// > array("1" => 1,"2.1" => "2.1","2.2.1" => "2.2.1","3" => "3","4.1" => "4.1")
foreach($newArray as $key => $value) {
echo $key." => ".$value."<br/>";
}
// > 1 => 1
// > 2.1 => 2.1
// > 2.2.1 => 2.2.1
// > 3 => 3
// > 4.1 => 4.1

Count the number of occurences of a particular value inside loop

In array count all true where category is 1 after counting the category will move to 2 thn count all true and so on?
Array generated:
foreach($_POST as $key => $data)
{
$a = explode("_", $key);
$f = array(
'category' => $a[1],
'answer' => $data
);
$f_data[] = $f;
}
FROM
Array
(
[0] => Array
(
)
[1] => Array
(
[category] => 1
[answer] => true
)
[2] => Array
(
[category] => 1
[answer] => true
)
[3] => Array
(
[category] => 1
[answer] => true
)
[4] => Array
(
[category] => 1
[answer] => false
)
[5] => Array
(
[category] => 1
[answer] => false
)
[6] => Array
(
[category] => 1
[answer] => true
)
[7] => Array
(
[category] => 1
[answer] => true
)
[8] => Array
(
[category] => 2
[answer] => true
)
[9] => Array
(
[category] => 2
[answer] => true
)
[10] => Array
(
[category] => 2
[answer] => true
)
[11] => Array
(
[category] => 2
[answer] => false
)
[12] => Array
(
[category] => 2
[answer] => true
)
[13] => Array
(
[category] => 2
[answer] => true
)
)
To
array (
category: 1,
count: 5
),
array(
category: 2,
count: 5
)
This is the solution :
$return = array();
foreach($cont as $item) {
if($item['answer'] == 'true') {
$verify = false;
foreach($return as $key => $value) {
if($value['category'] == $item['category']) {
$return[$key]['count']++;
$verify = true;
break;
}
}
if(!$verify)
$return[] = array('category' => $item['category'], 'count' => 1);
}
}
And this is better solution...
$return = array();
foreach($cont as $item) {
if($item['answer'] == 'true') {
if(array_key_exists($item['category'], $return))
$return[$item['category']]++;
else
$return[$item['category']] = 1;
}
}
Untested, but I believe this is what you are after (pending any minor mistakes):
foreach($_POST as $key => $data)
{
$a = explode("_", $key);
$f[$a[1]]['category'] = $a[1];
if ($data == "true") {
$f[$a[1]]['answer']++;
}
}

The simplest question: extract values from array

So this is an example:
Array (
[0] => Array ( [title] => Title_1 [checkout] => 1 [no_gateway] => 0 )
[1] => Array ( [title] => Title_2 [checkout] => 1 [no_gateway] => 1 )
[2] => Array ( [title] => Title_3 [checkout] => 0 [no_gateway] => 0 )
[3] => Array ( [title] => Title_4 [checkout] => 1 [no_gateway] => 1 )
[4] => Array ( [title] => Title_5 [checkout] => 0 [no_gateway] => 0 )
[5] => Array ( [title] => Title_6 [checkout] => 1 [no_gateway] => 0 )
)
I need to print out all values under [title] key having [checkout] => 1 & [no_gateway] => 0
In my case it should looks like
Title_1
Title_6
Please help php-beginner :) Thanks!
foreach($array as $row) {
if ($row['checkout'] && !$row['no_gateway']) {
print $row['title'];
}
}
foreach ($items as $item) {
if($item['checkout'] == 1 && $item['no_gateway'] == 0) {
echo $item['title'];
}
}
assuming your array is called $items
print_r(
array_map(function ($a) { return $a["title"]; },
array_filter($original,
function ($a) { return $a["checkout"] && !$a["no_gateway"]; }
)
)
);
You tagged the question with the answer: foreach
// assuming $arr is the array containing the values from the example
foreach ($arr as $record) {
if ($record['checkout'] && !$record['no_gateway']) {
echo $record['title'], "\n";
}
}
foreach( $array as $value ) {
if( $value["checkout"] == 1 && $value["no_gateway"] == 0 ) {
print $value["title"].PHP_EOL;
}
}

Categories