php array operations - php

I have the following 2D array and I would like to compare some values. First I would like to get the highest value from the array and depends on time extract from the previous value with the same index.
example: highest(work_something(223))-previous(work_something(120))
$data = array(
0 => array(
'time' => '2011-10-03 18:43:00',
),
1 => array(
'time' => '2011-10-03 18:44:00',
),
2 => array(
'time' => '2011-10-03 18:45:00',
'item_something' => -17,
'keyword_something' => 0,
'keyword_something_1' => 0,
'search_something' => 0,
'search_links_something' => 0,
'work_something' => 120,
),
3 => array(
'time' => '2011-10-03 18:45:00',
'item_something' => -17,
'keyword_something' => 0,
'keyword_something_1' => 0,
'search_something' => 0,
'search_links_something' => 0,
'work_something' => 223,
),
);

$array //This is your 2D array
$highest = 0;
foreach($array as $key => $value):
if(isset($value['work_something'])){
if($value['work_something'] > $highest){
$highest = $value['work_something']; //This is highest 'work_something' value
$highest_array_key = $key; //This is the key of 'work_something' array
}
}
endforeach;
//To compare with previews element use
$array[$highest_array_key - 1] //this is prew element
example: highest(work_something(223))-previous(work_something(120))
$highest - $array[$highest_array_key - 1]['work_something'];

Related

arrays with dif keys inside 1 array

like the question says, I have 2 foreach cycles, 1 cycle iterates an array with 4 keys, and the other one an array with 3 keys, how to get this two arrays in only 1 ?
I have this
....
],
],
'Detalle' => array()
];
foreach ($datos["line_items"] as $line => $item) {
$tempArray = array(
'NmbItem' => $item['name'],
'QtyItem' => $item['quantity'],
'PrcItem' => $item['price'],
'IndExe' => 1
);
}
foreach($datos["fee_lines"] as $line => $fee){
$tempArray=array(
'NmbItem' => $fee['name'],
'QtyItem' => 1,
'PrcItem' => $fee['total']
);
}
$dte['Detalle'][] = $tempArray;
}
if you notice the second array cycle doesnt contain 'indexe' key, after asign this tempArray in $dte['Detalle'][] = $tempArray only works with the last cycle, or the first one if I remove the second.
the output should be something like:
temp = Array (
array[0]
'NmbItem => name',
'QtyItem'=> 10,
'PrcItem'= 1000,
'IndExe' => 1
array[1]
'NmbItem => another name',
'QtyItem'=> 5,
'PrcItem'=> 3000
)
To make it work with your code, you should also add $dte['Detalle'][] = $tempArray; after the first loop.
The issue is that you are setting the $tempArray in each foreach so you end up with only the last one when assigning it in the $dte['Detalle'].
So, something like this should work:
foreach ($datos["line_items"] as $line => $item) {
$tempArray = array(
'NmbItem' => $item['name'],
'QtyItem' => $item['quantity'],
'PrcItem' => $item['price'],
'IndExe' => 1
);
}
$dte['Detalle'][] = $tempArray;
foreach($datos["fee_lines"] as $line => $fee){
$tempArray=array(
'NmbItem' => $fee['name'],
'QtyItem' => 1,
'PrcItem' => $fee['total']
);
}
$dte['Detalle'][] = $tempArray;
However, I would do it using the array_map function.
Docs for array_map
You can have it something like this:
<?php
$data_1 = array_map(function($item){
return array(
'NmbItem' => $item['name'],
'QtyItem' => $item['quantity'],
'PrcItem' => $item['price'],
'IndExe' => 1
);
}, $datos["line_items"]);
$data_2 = array_map(function($fee){
return array(
'NmbItem' => $fee['name'],
'QtyItem' => 1,
'PrcItem' => $fee['total']
)
}, $datos["fee_lines"]);
$dte['Detalle'] = array_merge($dte['Detalle'], $data_1, $data_2);

Mix array values with all possbile other values of an other Array

I have the following array and want to mix all values of the first array (21) with all other array offsets:
$option_variations = array(
'21' => array(
'standard_options' => array(81, 82, 80, 79),
),
'19' => array(
'standard_options' => array(77, 71, 70, 69,90,72,91,73),
),
'2' => array(
'pso_options' => array(8),
),
);
I found a sampling method in another post that mixed all possible values, but that's not what I need.
$new_array = array();
foreach($option_variations as $option_id => $option_arrays){
foreach($option_arrays as $option => $option_array){
}
/*
foreach($result_data as $option => $option_id){
$new_array[$option][] = $option_id;
}
*/
}

how to calculate the sum of same array values in PHP

I have an array like this
$estimate[0]=>
'gear' =>'MMG'
'total' => 315
'efforts' => 9
'afh' => 18
$estimate[1]=>
'gear' =>'MMG'
'total' => 400
'efforts' => 2
'afh' => 6
$estimate[2]=>
'gear' =>'BOO'
'total' => 200
'efforts' => 20
'afh' => 16
$estimate[3]=>
'gear' =>'BOB'
'total' => 250
'efforts' => 20
'afh' => 16
I want to calculate the sum of total, efforts and afh in which gear is same and it will be stored in the another array. Following my coding is working when the array (estimate) size is less than 5.
$calculate = array();
for($et=0;$et<count($estimate);):
if($et==0):
$calculate[$et]['gear'] = $estimate[$et]['gear'];
$calculate[$et]['total'] = $estimate[$et]['total'];
$calculate[$et]['efforts'] = $estimate[$et]['efforts'];
$calculate[$et]['afh'] = $estimate[$et]['afh'];
goto loopend;
endif;
for($cet=0;$cet<count($calculate);$cet++):
if($estimate[$et]['gear'] == $calculate[$cet]['gear']):
$calculate[$cet]['total'] = $calculate[$cet]['total'] + $estimate[$et]['total'];
$calculate[$cet]['efforts'] = $calculate[$cet]['efforts'] + $estimate[$et]['efforts'];
$calculate[$cet]['afh'] = $calculate[$cet]['afh'] + $estimate[$et]['afh'];
goto loopend;
endif;
endfor;
$calculate[$et]['gear'] = $estimate[$et]['gear'];
$calculate[$et]['total'] = $estimate[$et]['total'];
$calculate[$et]['efforts'] = $estimate[$et]['efforts'];
$calculate[$et]['afh'] = $estimate[$et]['afh'];
goto loopend;
loopend:$et++;
endfor;
The coding is not working more than many gears. Sometimes it works. I can't find the issues. Please help me to solve the issues.
You might use array_reduce:
$result = array_reduce($estimate, function($carry, $item) {
if (!isset($carry[$item["gear"]])) {
$carry[$item["gear"]] = $item;
return $carry;
}
$carry[$item["gear"]]["total"] += $item["total"];
$carry[$item["gear"]]["efforts"] += $item["efforts"];
$carry[$item["gear"]]["afh"] += $item["afh"];
return $carry;
});
Demo
As per my comment use foreach loop when your array length is not define
Here is your desired code
<?php
$estimate = array(
"0" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
"1" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
"2" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
);
$gear=0;
$total=0;
$efforts=0;
$afh=0;
foreach ($estimate as $key => $value) {
$gear=$gear+$value['gear'];
$total=$gear+$value['total'];
$efforts=$gear+$value['efforts'];
$afh=$gear+$value['afh'];
}
echo "<pre>";
$result = array('gear' => $gear, 'total' => $total,'efforts' => $efforts,'afh' => $afh);
echo "<pre>";
print_r($result);
you can check the result HERE
<?php
$new_arr = array();
$estimate[0] =array(
'gear' =>'MMG',
'total' => 315,
'efforts' => 9,
'afh' => 18
);
$estimate[1]=array(
'gear' =>'MMG',
'total' => 400,
'efforts' => 2,
'afh' => 6,
);
$estimate[2]=array(
'gear' =>'BOO',
'total' => 200,
'efforts' => 20,
'afh' => 16,
);
$estimate[3]=array(
'gear' =>'BOB',
'total' => 250,
'efforts' => 20,
'afh' => 16,
);
foreach ($estimate as $key => $value) {
$new_arr[$value['gear']] = array(
'total' => (isset($new_arr[$value['gear']]['total']) ? ($new_arr[$value['gear']]['total'] + $value['total']) : $value['total'] ),
'efforts' => (isset($new_arr[$value['gear']]['efforts']) ? ($new_arr[$value['gear']]['efforts'] + $value['efforts']) : $value['efforts'] ),
'afh' => (isset($new_arr[$value['gear']]['afh']) ? ($new_arr[$value['gear']]['afh'] + $value['afh']) : $value['afh'] )
);
}
echo "<pre>";print_r($new_arr);

PHP array for google chart; loop thru array and group by 2

(In between Christmas meals) I am again stuck with the loop through array and group by logic.
here is the array I am given
$aTest = Array
(
Array
(
'date' => 2017-05-04,
'period' => 'period2',
'category' => 'Indoor room',
'score' => 1
),
Array
(
'date' => 2017-05-04,
'period' => 'period5',
'category' => 'Indoor room',
'score' => 1
),
Array
(
'date' => 2017-05-04,
'period' => 'period2',
'category' => 'Indoor room',
'score' => 2
),
Array
(
'date' => 2017-05-04,
'period' => 'period4',
'category' => 'Indoor room',
'score' => 1
),
Array
(
'date' => 2017-05-03,
'period' => 'period5',
'category' => 'Gym Class',
'score' => 1
),
Array
(
'date' => 2017-05-03,
'period' => 'period1',
'category' => 'Gym Class',
'score' => 1
),
Array
(
'date' => 2017-05-03,
'period' => 'period4',
'category' => 'Indoor room',
'score' => 1
)
);
This time I like group by category and sum the score group by period. Y-axis will be the category and X-axis will be the period. In the end I need this for a google chart
/*period, total indoor, total gym, 'total indoor', 'total gym'*/
array(
['Period1', 0,1,'0','1'],
['Period2', 3,0,'3','0'],
['Period3', 0, 0,'0','0'],
['Period4', 4,0,'4','0'],
['Period5', 1,1,'1','1']
)
I have this php code:
foreach ($aTest as $value) {
//echo $value['period'].' - '.$value['score'].'<br/>';
if (empty($output[$value]['period']))
$output[$value]['period'] = ['Period1' => 0, 'Period2' => 0, 'Period3' =>0, 'Period4' => 0, 'Period5' => 0];
if(empty($output[$value]['category']))
$output[$value['catgeory']] = ['Gym Class' => 0, 'Indoor room' =>0];
$output[$value['category']] += $value['score'];
}
ksort($output);
but this only totals the score by Category and not by period.
I think I need to loop through the periods as well, but how?
You have a wrong logic here.
if (empty($output[$value]['period']))
$output[$value]['period'] = ['Period1' => 0, 'Period2' => 0, 'Period3' =>0, 'Period4' => 0, 'Period5' => 0];
that $value is an array and you try to check $output[$value]
I saw that you don't have any line sum periods Value.
I have a solution for your data.
What is my code do??
Sum score of the period by the category
For each merge period and category score to an array using arraySort category to set position of these category scores values
$temp = [];
$output = [];
foreach($aTest as $value){
$period = $value['period'];
$category = $value['category'];
// Create default values
if (empty($temp[$period])){
$temp[$period] = [];
}
if(empty($temp[$period][$category])){
$temp[$period][$category] = 0;
}
//Sum score
$temp[$period][$category] += $value['score'];
}
//After Forech we have an array with ['period name' => ['category name' => score]];
//Sort values of the category change it if you want, you can add more option such as (item type for add '' to values)
$arraySort = [
"Indoor room", //total indoor,
"Gym Class", // total gym,
"Indoor room", //'total indoor',
"Gym Class" //'total gym'
];
foreach($temp as $period => $catsScore){
$periodItem = [$period];
foreach($arraySort as $cat){
$periodItem[] = $catsScore;
}
$output[] = $periodItem;
}

how to find a element in a nested array and get its sub array index

when searching an element in a nested array, could i get back it's 1st level nesting index.
<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k, $search_query){
global $cnt;
if($v == $search_query){
/* i want the sub array index to be returned */
}
}
?>
i.e to say, if i'am searching 'victor', i would like to have 'dep1' as the return value.
Could anyone help ??
Try:
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($coll), RecursiveIteratorIterator::SELF_FIRST);
/* These will be used to keep a record of the
current parent element it's accessing the childs of */
$parent_index = 0;
$parent = '';
$parent_keys = array_keys($coll); //getting the first level keys like dep1,dep2
$size = sizeof($parent_keys);
$flag=0; //to check if value has been found
foreach ($iter as $k=>$val) {
//if dep1 matches, record it until it shifts to dep2
if($k === $parent_keys[$parent_index]){
$parent = $k;
//making sure the counter is not incremented
//more than the number of elements present
($parent_index<$size-1)?$parent_index++:'';
}
if ($val == $name) {
//if the value is found, set flag and break the loop
$flag = 1;
break;
}
}
($flag==0)?$parent='':''; //this means the search string could not be found
echo 'Key = '.$parent;
Demo
This works , but I don't know if you are ok with this...
<?php
$name = 'linda';
$col1=array ( 'dep1' => array ( 'fy' => array ( 0 => 'john', 1 => 'johnny', 2 => 'victor', ), 'sy' => array ( 0 => 'david', 1 => 'arthur', ), 'ty' => array ( 0 => 'sam', 1 => 'joe', 2 => 'victor', ), ), 'dep2' => array ( 'fy' => array ( 0 => 'natalie', 1 => 'linda', 2 => 'molly', ), 'sy' => array ( 0 => 'katie', 1 => 'helen', 2 => 'sam', 3 => 'ravi', 4 => 'vipul', ), 'ty' => array ( 0 => 'sharon', 1 => 'julia', 2 => 'maddy', ), ), );
foreach($col2 as $k=>$arr)
{
foreach($arr as $k1=>$arr2)
{
if(in_array($name,$arr2))
{
echo $k;
break;
}
}
}
OUTPUT :
dept2
Demo

Categories