Get Sum of Values using array_combine? - php

I am trying to count the total sum of values using array_combine. I have the duplicate key also, for example i have the array of emailid and array of product price.
$data1 = array("email1#example.com","email2#example.com","email1#example.com");
and $data2 = array("100","200","300");
Now in $data1 i have two duplicate values as email1#example.com
I am trying to use array_combine() It ignore the duplicate values and add the new one
I get this result as
email1#example.com => 300;
email2#example.com => 200;
But i want the result should be
email1#example.com => (400)100+300;
email2#example.com => 200;
Not sure how to get this result with array_combine Is something any alternatives to achieve this ?
Any Suggestion would be great.

Write a simple loop:
$result = array();
foreach ($data1 as $i => $v) {
if (!isset($result[$v])) {
$result[$v] = 0;
}
$result[$v] += $data2[$i];
}

Related

PHP create 1 array of 4 arrays ordered by index

I have 4 arrays, each one holds another column of a table, I would like to create one array with the data ordered per array[$i]. All arrays have the same number of values: $namesArr, $folderArr, $updatedAt, $valuesArr .
I would like my new array to be contain:
$namesArr[0], $folderArr[0], $updatedAt[0], $valuesArr[0],
$namesArr[1], $folderArr[1], $updatedAt[1], $valuesArr[1],
$namesArr[2], $folderArr[2], $updatedAt[2], $valuesArr[2],
...
I guess the solution is pretty simple, but I got stuck :(
Can anyone help?
I would do something like:
$arr = array_map(function () { return func_get_args(); },$namesArr, $folderArr, $updatedAt, $valuesArr);
You can use foreach loop to merge 4 arrays:
foreach ($namesArr as $key => $value) {
$arr[$key][] = $value;
$arr[$key][] = $folderArr[$key];
$arr[$key][] = $updatedAt[$key];
$arr[$key][] = $valuesArr[$key];
}
Thus $arr will be the merged array
<?php
$newArr = array();
for ($i = 0; $i < count($namesArr); $i++)
{
$newArr[$i][0] = $namesArr[$i];
$newArr[$i][1] = $folderArr[$i];
$newArr[$i][2] = $updatedAt[$i];
$newArr[$i][3] = $valuesArr[$i];
}
?>
Explanation
What this will do is iterate depending on how many elements there are in $namesArr.
I utilised a multidimensional array here so that the first set of square brackets is effectively the "row" in a table, and the second set of square brackets are the "column" of a table.
do the following way:
while($db->query($sql)){
$namesArr[] =$db->f('names');
$folderArr[]=$db->f('folder');
$updatedAt[]=$db->f('updated');
$valuesArr[]=$db->f('values');
}

PHP Array of Price Ranges - Retrieve the lowest and highest

I'm working with a PHP array that shows a range of prices, where an individual item is in the form of "price from-price to". Here's an example of the array:
Array
(
[0] => $625,000-$700,000
[1] => $550,000-$625,000
[2] => $1,000,000-$1,250,000
[3] => $925,000-$1,000,000
)
I now need to retrieve the lowest and highest price in the array, however as they are a range I first need to pull apart each price in each array item. For example using the above array I would like to be able to return something like this:
$minPrice = 550000;
$maxPrice = 1250000;
I'm new to PHP and completely stumped at this point about how to go about parsing each of the values from each array item then getting the lowest/highest value.
I would put all the normalized prices in an array and use the php max, min functions.
<?php
$ranges = array(
"$625,000-$700,000",
"$550,000-$625,000",
"$1,000,000-$1,250,000",
"$925,000-$1,000,000",
);
$prices = array();
foreach ($ranges as $range) {
$prices = array_merge($prices, explode("-", preg_replace("/[\\$,]/i", "", $range)));
}
$maxPrice = max($prices);
$minPrice = min($prices);
try this:
$array = Array
(
0 => '$625,000-$700,000',
1 => '$550,000-$625,000',
2 => '$1,000,000-$1,250,000',
3 => '$925,000-$1,000,000',
);
$tmp = array();
foreach($array as $key=>$value){
$cleanValue = explode('-', str_replace(array('$',','), array('',''), $value));
foreach($cleanValue as $k=>$v){
$tmp[] = $v;
}
}
$minValue = min($tmp);
$maxValue = max($tmp);
echo $minValue . ' '. $maxValue;
Please refer code below.
First value are exploded to an array and then "$" is removed and then value is converted to integer. Then values are added to array and finally min / max functions are called.
$maxPrice = 0;
$max_curr = 0;
$price_arr = array();
foreach($min_maxs as $min_max){
$min_max_arr = explode("-",$min_max); // string to array
array_walk($min_max_arr,"remove_dollar_commas"); // remove "$"
$price_arr = array_merge($price_arr , $min_max_arr ); // add to final array
}
$maxPrice = max($price_arr); // call max function to get maximum value
$minPrice = min($price_arr); // call min function to get minimum value
function remove_dollar_commas(&$subject){
$subject = intval( str_replace(array("\$",","), "", $subject) );
}

PHP get ranges of same values from array

Is there any way to get the key range of same values and make a new array?
Let's say we have an Array Like this in php :
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b','6'=>'a','7'=>'a'];
How can i get this array? Is there any function for this?
$second_array = ['1-3'=>'a','4-5'=>'b','6-7'=>'a'];
Loop through it, extract the keys, generate the ranges and insert to the new array -
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b'];
$flip = array();
foreach($first_array as $key => $val) {
$flip[$val][] = $key;
}
$second_array = [];
foreach($flip as $key => $value) {
$newKey = array_shift($value).' - '.end($value);
$second_array[$newKey] = $key;
}
Output
array(2) {
["1 - 3"]=>
string(1) "a"
["4 - 5"]=>
string(1) "b"
}
regarding your first question you can get range of each value using foreach() loop.
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b'];
foreach($first_array as $key=>$value)
{
//do your coding here, $key is the index of the array and $value is the value at that range, you can use that index and value to perform array manipulations
}
Regarding your second question it not exactly clear what are trying to implement there. But what ever you want to do like creating a new array with modified index and other things can be done within this foreach() loop itself
I hope this helps you.
If someone is still looking for an answer, here is what I did.
Given the array
$first_array = ['0'=>'a',
'1'=>'a',
'2'=>'a',
'3'=>'a',
'4'=>'a',
'5'=>'b',
'6'=>'b',
'7'=>'a',
'8'=>'a']
I build a multidimensional array, in which each element is an array of three more elements:
[0] - The value in the first array
[1] - The key where the value starts repeating
[2] - The last key where the value stops repeating
The code
$arrayRange = [];
for($i = 0; $i < count($first_array); $i++){
if(count($arrayRange) == 0){
// The multidimensional array is still empty
$arrayRange[0] = array($first_array[$i], $i, $i);
}else{
if($first_array[$i] == $arrayRange[count($arrayRange)-1][0]){
// It's still the same value, I update the value of the last key
$arrayRange[count($arrayRange)-1][2] = $i;
}else{
// It's a new value, I insert a new array
$arrayRange[count($arrayRange)] = array($first_array[$i], $i, $i);
}
}
}
This way you get a multidimensional array like this:
$arrayRange[0] = array['a', 0, 4];
$arrayRange[1] = array['b', 5, 6];
$arrayRange[2] = array['a', 7, 8];

Randomly Unset Element in Multidimensional Array if key-value Exists

I have a multidimensional array in PHP taking on the form of the following:
$data = array(
array('spot'=>1,'name'=>'item_1'),
array('spot'=>2,'name'=>'item_2'),
array('spot'=>1,'name'=>'item_3'),
);
If more than one array element contains a duplicate for the 'spot' number I would want to randomly select a single one and unset all other elements with the same 'spot' value. What would be the most efficient way to execute this? The resulting array would look like:
$data = array(
array('spot'=>2,'name'=>'item_2'),
array('spot'=>1,'name'=>'item_3'),
);
Store the values of spot in another array. Using array_count_values check which values occur more than once. Find the keys for those values. Select a random key. Delete all keys except the selected key from the original array. Here is the code:
$data = array(
array('spot'=>1,'name'=>'item_1'),
array('spot'=>2,'name'=>'item_2'),
array('spot'=>1,'name'=>'item_3'),
);
$arr = array();
foreach($data as $val){
$arr[] = $val['spot'];
}
foreach(array_count_values($arr) as $x => $y){
if($y == 1) continue;
$keys = array_keys($arr, $x);
$rand = $keys[array_rand($keys)];
foreach($keys as $key){
if($key == $rand) continue;
unset($data[$key]);
}
}

php looping through 2D array

I access the following values like this.
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[0]->Price
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[0]->Low
//next row
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[1]->Price
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[1]->Low
However I need to consolidate this to
$values[0][price]
$values[0][low]
$values[1][price]
$values[1][low]
2 other strange things. The values are strings and I need them to be decimals(2 decimal points) and also the min and the max for price and low accross all the rows
Well the obvious way to build an array of values would be:
$values = array();
for($i = 0; $i < some_maximum_value; $i++) {
$values[$i] = array(
'price' => $result->{'HistoricalPricesResult'}->HistoricalPricesResult[$i]->Price,
'low' => $result->{'HistoricalPricesResult'}->HistoricalPricesResult[$i]->Low,
);
}
TADAAAAAA!!!!
$values = array();
foreach($result->{'HistoricalPricesResult'}->HistoricalPricesResult as $key => $obj){
$values[$key]['price'] = $obj->Price;
$values[$key]['low'] = $obj->low;
}
$myVals = array();
foreach ($result->{'HistoricalPricesResult'}->HistoricalPricesResult as $key => $v)
{
$myVals[$key]['price'] = 1.0 * $c->Price; //hoping string has 2 after the decimal
$myVals[$key]['low'] = 1.0 * $c->Low
}
Try to figure out max/min yourself
Check out foreach loops and string/float conversion
http://us2.php.net/manual/en/control-structures.foreach.php
http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion

Categories