I have a multidimensional array
$array1 = array(
0 => array(34554, 45, 4545454),
1 => array(434534, 35, 345345),
2 => array(43534, 35, 4343445),
3 => array(35534, 34, 342323)
);
Can we find the minimum and maximum value for each value? if we want to find min for first and second column, the other column is max, and the result array is
$array2 = array(
0=>34554,
1=>34,
2=>4545454
);
i've tried this to get min
$result = array(); // save result
array_walk_recursive($ary, function($v, $k) use (&$result) {
if (!isset($result[$k])) $result[$k] = $v;
elseif ($result[$k] > $v) $result[$k] = $v;
});
print_r ($result);
and tried this to get max
$result = array(); // save result
array_walk_recursive($ary, function($v, $k) use (&$result) {
if (!isset($result[$k])) $result[$k] = $v;
elseif ($result[$k] < $v) $result[$k] = $v;
});
print_r ($result);
Thank you.
try below solution:
$array1 = array(
0 => array(34554, 45, 4545454),
1 => array(434534, 35, 345345),
2 => array(43534, 35, 4343445),
3 => array(35534, 34, 342323)
);
//max values
$max_arr = array_map(function ($val) {
return max($val);
}, $array1);
print_r($max_arr);
//min values
$min_arr = array_map(function ($val) {
return min($val);
}, $array1);
print_r($min_arr);
//min and max values
$min_max_arr = array_map(function ($val) {
return array('min' => min($val), 'max' => max($val));
}, $array1);
print_r($min_max_arr);
output:
//max values
Array
(
[0] => 4545454
[1] => 434534
[2] => 4343445
[3] => 342323
)
//min values
Array
(
[0] => 45
[1] => 35
[2] => 35
[3] => 34
)
//min and max values
Array
(
[0] => Array
(
[min] => 45
[max] => 4545454
)
[1] => Array
(
[min] => 35
[max] => 434534
)
[2] => Array
(
[min] => 35
[max] => 4343445
)
[3] => Array
(
[min] => 34
[max] => 342323
)
)
I have added some more element so that you can notice how it works, I have arranged max min as key and value pair, if you will edit your question and show me what you want as output, I will update it.
<?php
$array1 = array(
0 => array(34554, 45, 4545454),
1 => array(434534, 35, 345345),
2 => array(43534, 35, 4343445),
3 => array(9355434, 34, 342323),
4 => array(35534, 34, 342323),
5 => array(8544534, 34, 342323),
6 => array(35534, 34, 342323)
);
foreach($array1 as $arr1){
$max = max($arr1);
$arr[$max] = min($arr1);
}
var_dump($arr);
output
array (size=6)
4545454 => int 45
434534 => int 35
4343445 => int 35
9355434 => int 34
342323 => int 34
8544534 => int 34
Related
I need to sum the values in element 1 of my array where the values in element 0 are duplicate.
Here's a small piece of my array
Array
(
[0] => 3
[1] => 1
)
Array
(
[0] => 3
[1] => 2
)
Array
(
[0] => 3
[1] => 128
)
Array
(
[0] => 39
[1] => 4
)
The results i'm expecting to see
Array
(
[0] => 3
[1] => 131
)
Array
(
[0] => 39
[1] => 4
)
I'm still really new to PHP so any help is greatly appreciated.
You can use a combination of array_intersect, array_column and array_sum to only iterate twice. (One for each unique column 0 value).
$col0 = array_column($arr, 0);
$col1 = array_column($arr, 1);
Foreach(array_unique($col0) as $val){
$res[] = [$val, array_sum(array_intersect_key($col1, array_intersect($col0,[$val])))];
}
Var_dump($res);
https://3v4l.org/gKb5b
The way I've done it is made sure all duplicates where put in the same array.
// Your data
$sample = [[3, 1],[3, 2],[3, 128],[39, 4]];
foreach($sample as $array){
$tmp[$array[0]][] = $array[1];
}
# Output: {"3":[1,2,128],"39":[4]}
Now sum the arrays, and put it back to the structure it originally was.
foreach($tmp as $k => $v){
$new[] = [$k, array_sum($v)];
}
# Output: [[3,131],[39,4]]
But many roads lead to Rome.
Try this code. It may help you.
$array = array(["0" => 3, "1" => 1] , ["0" => 3, "1" => 2], ["0" => 3, "1" => 128], ["0" => 39, "1" => 4]);
$finalArray = [];
foreach($array as $a) {
$finalArray[$a[0]][0] = $a[0];
$finalArray[$a[0]][1] = !isset($finalArray[$a[0]][1]) ? $a[1] : $finalArray[$a[0]][1] + $a[1];
}
echo '<pre>';
print_r($finalArray);
exit;
You could do something like this. I have separated into two foreach. Hope it helps.
<?php
$a = [[3,1],[3,2],[3,128],[39,4]];
$result=[];
$temp = [];
foreach($a as $line) {
$temp[$line[0]] += $line[1];
}
foreach($temp as $k => $value) {
$result[]=[$k ,$value];
}
$data =
[
[3,1],
[3,2],
[3,128],
[39,4]
];
foreach($data as $item)
$sums[$item[0]] = ($sums[$item[0]] ?? 0) + $item[1];
$result = array_map(null, array_keys($sums), $sums);
var_export($result);
Output:
array (
0 =>
array (
0 => 3,
1 => 131,
),
1 =>
array (
0 => 39,
1 => 4,
),
)
$arr = [ [ 3, 1],[ 3, 2 ],[ 3, 128], [ 39, 4]];
$sum = [];
foreach($arr as $value) {
$sum[$value[0]][] = $value[1];
}
foreach($sum as $key=>$value ) {
$result[] = [ $key, array_sum($value)];
}
Output:
Array
(
[0] => Array
(
[0] => 3
[1] => 131
)
[1] => Array
(
[0] => 39
[1] => 4
)
)
I have a a array like below and i want min value and it's index for searching tax class id
Array
(
[tax_class_id] => Array
(
[0] => 12
[1] => 13
[2] => 13
)
[price] => Array
(
[0] => 6233
[1] => 3195
[2] => 19192
)
)
and i am searching least price and respective key in tax_class_id. In this Senario, i require lowest in price i.e 3195 and tax_id - 13 i.e key [1]
My Code is
$prod_total = array();
for($i = 1;$i <= $chunk;$i++){
if($i == 1) {
$min_product_amt = min($product_amt['price']);
$index = array_search($min_product_amt, $product_amt);
$product_total = $min_product_amt;
//ceil Round numbers up to the nearest integer
$prod_total['price'] = ceil($product_total * $discount/100);
$prod_total['tax_id'] = $product_amt['tax_class_id'];
//Remove the first element from an array
array_shift($product_amt['price']);
array_shift($product_amt['tax_class_id']);
} else {
$second_min_product_amt = min($product_amt['price']);
$index = array_search($min_product_amt, $product_amt);
$product_total = $second_min_product_amt;
$prod_total['price'] = ceil($product_total * $discount/100);
$prod_total['tax_id'] = $product_amt['tax_class_id'];
array_shift($product_amt['price']);
array_shift($product_amt['tax_class_id']);
}
}
print_r($prod_total);
die;
$array=Array
(
'tax_class_id' => Array
(
0 => 12,
1 => 13,
2 => 13
),
'price' => Array
(
0 => 6233,
1 => 3195,
2 => 19192
)
);
$minValue= min($array['price']);
$minKey=array_keys($array['price'], $minValue);
$tax_id=$array['tax_class_id'][$minKey[0]];
echo $tax_id;
This code will work for your issue. First i get the minimum value of nested array price and then it's associated key. After that i just access the nested array tax_class_id and get the value of the field i need like accessing every array.
$data = [
"tax_class_id" => [
12,
13,
13
],
"price" => [
6233,
3195,
19192
]
];
$lowestFound;
foreach($data["price"] as $i => $price){
if(!$lowestFound || $lowestFound[1] > $price)
$lowestFound = [$i,$price];
}
echo $data["tax_class_id"][$lowestFound[0]];
This code get tax_class_id of lowest price key in one cycle.
I think array_column gives you a nice output.
$array=Array
(
'tax_class_id' => Array(
0 => 12,
1 => 13,
2 => 13
),
'price' => Array(
0 => 6233,
1 => 3195,
2 => 19192
)
);
// Find minimum value
$min= min($array['price']);
// Find key of min value
$Key=array_search($min, $array['price']);
// Extract all values with key[min value]
$new = array_column($array, $Key);
Var_dump($new);
The output in $new will now be
array(2) {
[0]=> int(13)
[1]=> int(3195)
}
Basically both of the values you are looking for.
https://3v4l.org/NsdiS
I have an array like this
Array ( [item1] => pack1 [amount1] => 1 [price1] => 25 [amount2] => 1 [price2] => 45 [item3] => pack3 [amount3] => 4 [price3] => 65 [sender] => Submit )
I need to get the values item1 & item3 out of the array, then remove the item on them with a
str_replace
Then find largest number with
max
just the first part that is the toughest, any ideas?
foreach through the array, if the key contains item then get/set the values. Also check the value to see if it's greater than the previous to get the max
$a = array( "item1" => "pack1", "amount1" => 1, "price1" => 25, "amount2" => 1, "price2" => 45, "item3" => "pack3");
$b = array();
$pattern = '/item[1-9]/';
$max_index = 0;
foreach($a as $key => $value){
if(preg_match($pattern, $key, $matches, PREG_OFFSET_CAPTURE)){
$index = str_replace("item","",$key);
$b[$index] = $value;
if($index > $max_index){
$max_index = $index;
}
}
}
$max_value = $b[$max_index];
echo $max_value;
I'm looking for a way to shuffle an array by groups of values in PHP.
For example, I have a sorted array :
Array
(
[peter] => 100
[paul] => 100
[mary] => 50
[andrew] => 50
[bill] => 50
[jason] => 10
[sofia] => 10
)
And I'd like to shuffle it this way :
Array
(
[paul] => 100
[peter] => 100
[mary] => 50
[bill] => 50
[andrew] => 50
[jason] => 10
[sofia] => 10
)
Would you know a smart way to do this, or will I have to write a dirty foreach-based script ?
With this user defined function shuffle_assoc you can shuffle your array before sorting.
function shuffle_assoc(&$array) {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
$array = array('peter' => 100
, 'paul' => 100
, 'mary' => 50
, 'andrew' => 50
, 'bill' => 50
, 'jason' => 10
, 'sofia' => 10);
shuffle_assoc($array);
asort($array);
array_reverse($array);
var_dump($array);
I found the answer by using both arsort and the function shuffle_assoc() that is discribed in the first user contribution on this page : PHP: shuffle
function shuffle_assoc(&$array) {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
$array = array(
'peter' => 100,
'paul' => 100,
'mary' => 50,
'andrew'=> 50,
'bill' => 50,
'jason' => 10,
'sofia' => 10
);
shuffle_assoc($array);
arsort($array);
print_r($array);
I can't seem to wrap my head around this.
I am given an array in PHP that looks something like this:
array (
0 => array (
0 => 50,
1 => 0.80
),
1 => array (
0 => 300,
1 => 0.50
),
2 => array (
0 => 600,
1 => 0.30
),
3 => array (
0 => 1000,
1 => 0.20
),
4 => array (
0 => 4000,
1 => 0.10
)
);
An array of arrays where the first index of the inner array represents a quantity while the second index represents a price.
I want to import this data into my database, but in a specific way.
I have specific quantities that I like to keep track of that are defined by the following array:
array(10,100,500,1000,5000,10000);
I then want to make the original array more fine tuned to quantities and prices that I would like to see. So in this particular example, I would like an array that looks like this:
array (
0 => array (
0 => 100,
1 => 0.80
),
1 => array (
0 => 500,
1 => 0.50
),
2 => array (
0 => 1000,
1 => 0.20
),
3 => array (
0 => 5000,
1 => 0.10
)
);
My new array will only contain the specific quantity indexes.
If a quantity exists in the original array, I use that price. If it doesn't exist, I would use the price of the next lowest quantity. If no lower quantity exists, I don't want to see that quantity in the new array.
I have been able to accomplish what I want for the most part with the following code:
function getRelativePrices($pricearray) {
$relativeprices = array();
$types = array(10,100,500,1000,5000,10000);
foreach ($types as $q) {
$new_array = array();
foreach ($pricearray as $index => $array) {
if ($q >= $array[0]) {
$new_array = array($q, $array[1]);
}
}
if (sizeof($new_array)) {
$relativeprices[] = $new_array;
}
}
return $relativeprices;
}
The only problem with the above is that I am getting extra data that I do not want. In the example I provided, I am getting a 5th index/array at the end that looks like:
4 => array (
0 => 10000,
1 => 0.10
)
I don't want this last piece, since I find it redundant considering that I know that 5000 pieces cost $0.10 each, so I can assume that 10000 will cost the same price when "4000" is the highest quantity given in the original array.
So I want to ask for help in removing this last piece.
Also, I was wondering if someone had a better coding method in general for converting this array.
You could just do in your inner foreach:
foreach ($pricearray as $index => $array) {
if ($q >= $array[0]) {
if($q == 10000) { continue; }
$new_array = array($q, $array[1]);
}
}
OK I think this should do the trick. I think the problem was in your comparison... See code:
function getRelativePrices($pricearray) {
$relativeprices= array();
$types = array(10,100,500,1000,5000,10000);
foreach($pricearray as $p) {
$new_array = array();
foreach($types as $t) {
if($p[0] <= $t) {
$new_array = array($t,$p[1]);
break;
}
}
if(sizeof($new_array)) {
$relativeprices[] = $new_array;
}
}
return $relativeprices;
}
Here is an example of my test based on your code examples:
function getRelativePrices($pricearray) {
$relativeprices= array();
$types = array(10,100,500,1000,5000,10000);
foreach($pricearray as $p) {
$new_array = array();
foreach($types as $t) {
if($p[0] <= $t) {
$new_array = array($t,$p[1]);
break;
}
}
if(sizeof($new_array)) {
$relativeprices[] = $new_array;
}
}
return $relativeprices;
}
$test = array (
0 => array (
0 => 50,
1 => 0.80
),
1 => array (
0 => 300,
1 => 0.50
),
2 => array (
0 => 600,
1 => 0.30
),
3 => array (
0 => 1000,
1 => 0.20
),
4 => array (
0 => 4000,
1 => 0.10
)
);
print_r(getRelativePrices($test));
And the output was:
Array
(
[0] => Array
(
[0] => 100
[1] => 0.8
)
[1] => Array
(
[0] => 500
[1] => 0.5
)
[2] => Array
(
[0] => 1000
[1] => 0.3
)
[3] => Array
(
[0] => 1000
[1] => 0.2
)
[4] => Array
(
[0] => 5000
[1] => 0.1
)
)