This question already has answers here:
PHP Associative Array Duplicate Keys
(6 answers)
Closed 8 months ago.
I am a complete newbie at programming and am trying to create a function that combines the values of unique keys and then returns the highest value.
$arr = array(
"Canada"=>500,
"US"=>2,
"Mexico"=>40,
"Mexico"=>50,
"US"=>170,
"Canada"=>25,
"Mexico"=>5,
"US"=>300
);
Right now, if I print out the array, I get:
Array ( [Canada] => 25 [US] => 300 [Mexico] => 5 )
I want it to print out the following:
Canada = 525
I've tried during foreach loops, array_sum, array_map, array_reduce, but to no avail :(
As arrays always have unique keys I recommend you re-format your input array to an array of arrays like so
$arr = array(
array("Canada"=>500),
array("US"=>2),
array("Mexico"=>40),
array("Mexico"=>50),
array("US"=>170),
array("Canada"=>25),
array("Mexico"=>5),
array("US"=>300)
);
You can then parse this array in a loop - adding the values t0 $counter_array
$counter_array = array();
foreach ($arr as $arrays) {
foreach ($arrays as $key => $value) {
if (!isset($counter_array[$key])) {
$counter_array[$key] = 0;
}
$counter_array[$key] += $value;
}
}
print_r($counter_array);
Array
(
[Canada] => 525
[US] => 472
[Mexico] => 95
)
Array Data Structure require unique identifier for each value. It's due to the way it's stored in memory.
Ask yourself: How would program distinguish between the two keys?
In your example. Let's say I'm trying to fetch a value of $arr["Canada"].
You put 2 different values to that identifier (key). Logically, the last one will override the previous one. And that is what exactly will happen if you will try to instantiate this array.
In this case I would change the way of array instantiation to make it something like this:
$arr = [
"Canada" => [500, 25],
"US" => [2, 170, 300],
"Mexico" => [40, 50, 5]
];
$result = array_map(function ($e) {
return array_sum($e);
}, $arr);
var_export($result);
array ( 'Canada' => 525, 'US' => 472, 'Mexico' => 95)
Related
I have an array in PHP that shows an average number per month. Now this array can contain multiple entries for the same month. If that is the case, the numbers have to be summed up and divided by the count of entries per month:
E.g. May = (3.15 + 2.29 + 2.36) / 3 = 2.6
Input:
$result = [
0 => ['April' => 4.36],
1 => ['May' => 3.15],
2 => ['May' => 2.29],
3 => ['May' => 2.36]
];
Output:
$result = [
[0] => ['April' => 4.36],
[1] => ['May' => 2.60]
];
Any idea how this can be done?
Here In the first loop we are iterating over input array to gather values according to month, and in second loop we are using array_walk to loop-over the array to find average. using function array_sum and count
Try this code snippet here
<?php
ini_set('display_errors', 1);
$Array = [
0 => ['April' => 4.36],
1 => ['May' => 3.15],
2 => ['May' => 2.29],
3 => ['May' => 2.36]
];
$result=array();
//Gathering values according to months.
foreach ($Array as $value)
{
$result[key($value)][]=$value[key($value)];//using key function to get the first key of array
}
//using array_sum for finding sum of array.
array_walk($result,function($value,$key) use (&$newResult){
$newResult[] = array($key =>array_sum($value)/count($value));
});
print_r($newResult);
You can use multi-dimensional arrays.
Multi-dimensional arrays are arrays in arrays, how many ever times you wish.
https://www.w3schools.com/php/php_arrays_multi.asp
http://php.net/manual/en/language.types.array.php
So, relating to you code, let's say November has these numbers:
4,3,2 and 1.
You would do this:
$result = array(
"November" => array(4,3,2,1)
)
Then you would find the length of the array, access the multi-dimensional objects by doing this:
$result["November"][0]
(This will output 4)
Then write a foreach script to determine the average. I'll leave that to you.
try this, check the live demo
$array = [];
foreach($result as $v)
{
$array[key($v)][] = current($v);
}
$result = array_map(function($v){return array_sum($v)/count($v);}, $array);
I'm trying to find when the array has 2nd dimension values that are the same so I can deal with them.
I've looked at array_unique and other people who are asking a similar question, but they all delete the values instead of returning them.
Say I have an array like this:
array(
[0] => array(
[laps] => 7,
[corrected_time] => 18
),
[1] => array(
[laps] => 6,
[corrected_time] => 18
),
[2] => array(
[laps] => 7,
[corrected_time] => 18.5
)
)
I'd like to have it return: array(0,1) because they both have the same value for corrected time
Here is one approach. First get the values for corrected_time and convert them to strings (because we'll use them in array_count_values, which only works on ints and strings).
$times = array_map('strval', array_column($your_array, 'corrected_time'));
Then find all the values that occur more than once using array_count_values and array_filter.
$repeats = array_filter(array_count_values($times), function($time) {
return $time > 1;
});
After you have this list of repeated times, you can use it to filter your original array to only include items with repeated times.
$multiples = array_filter($your_array, function($item) use ($repeats){
return isset($repeats[(string) $item['corrected_time']]);
});
You can iterate over this, or if you only want the keys, you can get them with
$keys = array_keys($multiples);
This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 3 months ago.
I am new to php & I'm not sure that this can be done, but I am hoping that someone knows how to. I've collected all the data that I need to submit but now I need to reformat it before I can json_encode to send to the database.
Basically, I have 1 parent array($data) containing 3 sub-arrays ($hours, $WId, $Pid). I need to create associative arrays for each index position & join them together.
Here is my parent array:
$data = array(
'hours' => array(),
'wId' => array(),
'phaseId' => array(),
);
Here is what currently returns when I print_r each of these arrays:
Array ( [hours] => Array ( [0] => 0.5 [1] => 1 [2] => 2 ) )
Array ( [wId] => Array ( [0] => 10, [1] => 9, [2] => 8, ) )
Array ( [phaseId] => Array ( [0] => 20, [1] => 20, [2] => 19, ) )
I need to take these "vertical" arrays & turn them in to "horizontal" arrays per index, using thearray name as the $key & the value for that index as $value. Here is what I need to return.... (Syntax is probably wrong but you can get the idea.)
Array[1] ("hours" => 0.5, "wId" => 10, "phaseId" => 20)
Array[2] ("hours" => 1, "wId" => 9, "phaseId" => 20)
Array[3] ("hours" => 2, "wId" => 8, "phaseId" => 19)
Is there a function that will allow me to do this easily? I saw how to join & merge them together but not sure how to set the array name (hours, etc) as the $key & the value for each index as $value. I need to loop it too because the length of the arrays will vary. (But they will always the same length as each other, so index should still work as what needs to be collected.)
Any suggestions would be greatly appreciated :)
<?php
// set up your output array
$result = array();
// loop through $data, exposing $name for later use
foreach ($data as $name => $array) {
// loop through each named array and set the desired value
// using the current $key and $name
foreach ($array as $key => $value) {
$result[$key][$name] = $value;
}
}
// tada!
print_r($result);
NOTE: In your desired results in your question, you had the parent Array keys starting at 1. This answer assumes that's a typo and you actually wanted them to match the input. If you indeed wanted it to start at one, just change this line in my answer:
$result[$key+1][$name] = $value;
I have the following PHP array:
Array
(
[0] => 750
[1] => 563
[2] => 605
[3] => 598
[4] => 593
)
I need to perform the following action on the array using PHP:
Search the array for a value (the value will be in a
variable; let's call it $number). If the value
is present in the array, remove it.
If someone could walk me through how to do that, it would be much appreciated.
Note: If it makes it any easier, I can form the array so the keys are the same as the values.
$array = array_unique($array) // removes dupicate values
while(false !== ($num = array_search($num, $array))){
unset($array[$num]);
}
$max = max($array);
will search for all keys with value $num and unset them
lets say your $array
$array = array_unique($array) // removes dupicate values
$array = arsort($array)
$variable = $array[0] // the maximum value in the array, and place it in a variable.
$key = array_search($array, $number);
if($key){
unset($array[$key]) // Search array for a value, value is present in array, remove it.
}
array_search() and unset() seems a good method for your sample data in your question. I'll just show a different way for comparison's sake (or in case your use case is slightly different from what you have posted here).
Methods: (Demo)
$array=[750,563,605,598,593];
// if removing just one number apply the number as an array element
$number=605;
var_export(array_diff($array,[$number]));
// if you are performing this task with more than one $number, make $numbers=array() and do the same...
$numbers=[605,563]; // order doesn't matter
var_export(array_diff($array,$numbers));
// if you need to re-index the output array, use array_values()...
$numbers=[605,563]; // order doesn't matter
var_export(array_values(array_diff($array,$numbers)));
Output:
array (
0 => 750,
1 => 563,
3 => 598,
4 => 593,
)
array (
0 => 750,
3 => 598,
4 => 593,
)
array (
0 => 750,
1 => 598,
2 => 593,
)
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Sort an array by a child array's value in PHP
I have the following array structure:
$en_array = array();
while(...) {
$en_array[] = $row;
}
$en_array = array (
array (
"name" => "a",
"followers" => 5,
"imageurl" => "http://images.com/img.jpg"
)
array (
"name" => "b",
"followers" => 25,
"imageurl" => "http://images.com/img.jpg"
)
array (
"name" => "c",
"followers" => 15,
"imageurl" => "http://images.com/img.jpg"
)
)
In this example I would like to order the keys of en array by the values of followers, e.g. $en_array[0]["followers"] would have the value of 25.
I'm not entirely sure if this can be done, but I hope it can.
Any help will be much appreciated :)!!
Since it looks like you're only interested in sorting by followers, we can do this easily with PHP's usort.
function compare_by_followers($a, $b) {
if($a['followers'] == $b['followers']) return 0;
return $a['followers'] > $b['followers'] ? -1 : 1;
}
usort($en_array, 'compare_by_followers');
Sorting is, at its core, a process of comparing the array's elements to each other and figuring out which ones are greater than the others. usort allows you to use a custom comparison function for this process: compare_by_followers($a, $b) returns -1 if $a['followers'] is greater than $b['followers'] (meaning that $a should go before $b), returns 1 if $a['followers'] is less than $b['followers'] (meaning that $a should come after $b), and returns 0 if they are equal.
array_multisort() is what you are after.
foreach ($en_array as $key => $row) {
$name[$key] = $row['name'];
$followers[$key] = $row['followers'];
}
array_multisort($followers,SORT_DESC,$name,SORT_ASC,$en_array);
After this, results are in descending order of followers, and where followers are the same, ascending order of name (i.e. alphabetical order).