I just started learning php and I have this issue. I'm trying to loop through this array to get the total value of each key and output the student with the highest number. I'd really appreciate your inputs
$students = array(
'Mary' => [20,45,12],
'Grace' => [40,78,56],
'John' => [61,37,58]
);
The expected output should be Grace but i can't seem to get it to work.
You don't have to loop. Just calculate all the totals
$totals = array_map('array_sum', $students);
then output the key of the array with the maximum total.
echo array_keys($totals, max($totals))[0];
Something like this maybe assuming all grades will be positive
$students = array(
'Mary' => [20,45,12],
'Grace' => [40,78,56],
'John' => [61,37,58]
);
$highest_grade = 0;
$higest_person = "";
foreach($students as $key => $value) {
$max = max($value);
if ($highest_grade <= $max) {
$highest_grade = $max;
$highest_person = $key;
}
}
echo $highest_person . '->' . $highest_grade;
Output is using http://phptester.net/
Grace->78
Related
I'm trying to get the name of an array once I have found a specific value.
Specifically I'm looking to get the highest and lowest values within my array for a certain key, once I have those values I then need to get the name of the array holding those values.
My array looks like this -
Array
(
[123456] => Array
(
[value1] => 0.524
[value2] => 0.898
[value3] => -6.543
)
[246810] => Array
(
[value1] => 0.579
[value2] => 0.989
[value3] => -5.035
)
I have gotten the max value using this code -
max(array_column($statsArr, 'value1'));
This, correctly, gives me the value "0.579". I now need to get the value of the array holding this information so in this case I also want to get the value "246810". I don't know how to do this though, any help would be appreciated!
Iterate over your array with a simple foreach and save required key:
$max = 0;
$founded_key = false;
foreach ($array as $key => $value) {
if ($max < $value['value1']) {
$max = $value['value1'];
$founded_key = $key;
}
}
echo $founded_key, ' - ', $max;
For these kinds of problems I like using array_reduce. max is itself an array reduce operation which takes an array and returns a single value, PHP just offers it out of the box as convenience since it's a very common operation.
Here's an example code:
$array = array(
123456 => array(
'value1' => 0.524,
'value2' => 0.898,
'value3' => -6.543
),
246810 => array(
'value1' => 0.579,
'value2' => 0.989,
'value3' => -5.035
)
);
$maxKey = array_reduce(array_keys($array), function ($carry, $key) use ($array) {
if ($carry === null) {
return $key;
}
return $array[$key]['value1'] > $array[$carry]['value1'] ? $key : $carry;
}, null);
$maxValue = $array[$maxKey]['value1'];
Working example: http://sandbox.onlinephpfunctions.com/code/ecd400ffec91a6436c2fb5ee0410658e22772d4b
function getMax($array, $field) {
$maxValue = null;
$maxKey = null;
foreach($array as $key => $content) {
if (is_null($maxValue) || $content[$field] > $maxValue) {
$maxValue = $content[$field];
$maxKey = $key;
}
}
return [$maxValue, $maxKey];
}
You can search for the maximum value in the array_column.
I first prepare the array_column with correct keys by combining it, then find the max like you do.
Then we can array_search the value.
$value1 = array_combine(array_keys($statsArr), array_column($statsArr, 'value1'));
$max = max($value1);
echo $max . PHP_EOL;
$array = $statsArr[array_search($max, $value1)];
var_dump($array);
https://3v4l.org/Q9gOX
Alternatively you can array_values the $statsArr to make it 0 indexed just like the array_column.
$value1 = array_column($statsArr, 'value1');
$max = max($value1);
echo $max . PHP_EOL;
$array = array_values($statsArr)[array_search($max, $value1)];
var_dump($array);
I can't seem to get the same value in array. The first value just doesn't appear in the output. The code compares the id's and joins the values that match the id.This is my code:
<?php
$pic = array ('1.jpg','2.jpg','3.jpg');
$picid = array('aqua','green','orange');
$size = array('12','24','12');
$sizeid = array ('aqua','green','orange');
$newarray2 = array();
foreach (array_combine($pic, $picid) as $outpic => $outid) {
foreach (array_combine($size, $sizeid) as $outsize => $outsizeid) {
if ($outid == $outsizeid) {
$result = "$outpic $outsize";
$newarray2[]= $result;
} }
$result1 = implode(",", $newarray2);
echo $result1;
$newarray2 = array();
}
?>
The desired output I want to get is this:
1.jpg 12
2.jpg 24
3.jpg 12
But when I run the code I get this:
2.jpg 24
3.jpg 12
I think the first value is being overwritten somehow, but I don't know the way around this. What am I doing wrong?
You have multiple keys on 12, only the last one is used.
In the example below we add an additional layer to the keys, so that the keys can overlap.
$result = array();
foreach ($size as $i => $key) {
$result[] = array($key => $sizeid[$i]);
}
foreach ($result as $value) {
foreach($value as $outsize => $outsizeid){
if ($outid == $outsizeid) {
$result = "$outpic $outsize";
$newarray2[]= $result;
}
}
}
This makes more sense if you consider the result of calling "array_combine".
$picCombo = array_combine($pic, $picid);
$picCombo = array(
'1.jpg' => 'aqua',
'2.jpg' => 'green',
'3.jpg' => 'orange',
);
$sizeCombo = array_combine($size, $sizeid);
$sizeCombo = array(
'12' => 'aqua',
'24' => 'green',
'12' => 'orange',
);
In PHP, the syntax, in array definitions and foreach statements are:
key => value
Note that your keys and values are the opposite of what you want.
So, solutions:
array_combine($picid, $pic); // Reverse the arrays
Just define the array as I've done above, with $picCombo.
I have a multi dimensional array that I have got from a database and I want to check this array for duplicate data and store it in another array of duplicates. my code is as follows
//create temp array
$tmp = array();
foreach ($matchingarray as $nameKey => $match) {
// loop through and stoe the contents of that array to another so i can compare
$tmp[] = $match;
}
// create an array to store duplicates
$duplicatesArray = array();
// if the temp array is not empty then loop through both arrays
if (! empty($tmp)) {
foreach ($tmp as $key => $tmpvalue) {
foreach ($matchingarray as $key => $match) {
// if a key name is the same in both arrays then add it tothe duplicates array
if ($tmpvalue['name'] == $match['name']) {
$duplicatesArray = $match;
}
}
}
}
//count how many are duplicates
$dups = count($duplicatesArray);
What I would like to know is this the right logic?
I will take where Igoel left off
there is 1 error and also 1 suggest that i will make.
Error:
you cannot reuse $key twice in the foreach because they will override.
Suggestion as what Igoel stated: your best bet for duplicate effectively is to use sql. SQL is faster at processing than looping through arrays. Don't forget you need to load the data into memory and thats costly.
Try this way
<?php
static $cnt = array();
$min = 1;
$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){
global $cnt;
$cnt[] = $v;
}
array_walk_recursive($coll, 'recursive_search');
$newNumbers = array_filter(
array_count_values($cnt),
function ($value) use($min) {
return ($value > $min);
}
);
echo "Values > 1 are repeated \n";
print_r(array_count_values($cnt));
echo "Values repeted\n";
print_r($newNumbers);
DEMO
I have two arrays that I would like to join into one. Both arrays have a common key=>value and I would like to insert the values of one array to the other so that I to create one array.
$array1 = [
['ID' => 123456, 'Key' => 1000, 'value' => 123.45],
['ID' => 789012, 'Key' => 1001, 'value' => 56748.17],
];
$array2 = [
['Key' => 1000, 'description' => 'desc1'],
['Key' => 1001, 'description' => 'desc2'],
];
I would like to join Array2 with Array1 so that the resulting Array is as follows:
array (
0 =>
array (
'ID' => 123456,
'Key' => 1000,
'value' => 123.45,
'description' => 'desc1',
),
1 =>
array (
'ID' => 789012,
'Key' => 1001,
'value' => 56748.17,
'description' => 'desc2',
),
)
So the arrays have been joined using the [Key] value as the, well, key. I've looked at array_merge and other function but I can't seem to get these two arrays to "merge" properly.
try this, its linear
$keyval = array();
foreach($array1 as $item)$keyval[$item['Key']] = $item['value'];
foreach($array2 as $key=>$item)$array2[$key]['description'] = isset($keyval[$item['Key']]) ? $keyval[$item['Key']] : '';
You would have to do something like
$result = array();
foreach ($a1 as $v1)
{
foreach ($a2 as $k2 => $v2)
{
if ($v1['Key'] === $v2['Key'])
{
$result[] = array_merge($v1, $v2);
unset($a2[$k2]);
break;
}
}
}
Version with for loops
$result = array();
$c_a1 = count($a1);
$c_a2 = count($a2);
for ($i = 0; $i < $c_a1; $i++)
{
for ($j = 0; $j < $c_a2; $j++)
{
if ($a1[$i]['Key'] === $a2[$j]['Key'])
{
$result[] = array_merge($a1[$i], $a2[$j]);
unset($a2[$j]);
$c_a2--;
break;
}
}
}
This is my approach:
$temp_ array = array_fill_keys (array_map(create_function('$a', 'return $a["Key"];'), $array_1) , $array_1);
$result = array();
foreach ($array_2 as $item) {
if (isset($temp_array[$item['Key']])) {
$result[] = array_merge($item, $temp_array[$item['Key']]);
}
}
I have elaborated more in the code above, and reached this improved version:
function array_merge_items_by_common_key_value($key, $array_1, $array_2)
{
$result = array();
$temp_ array = array_fill_keys(array_map(create_function('$a', 'return $a["' . $key . '"];'), $array_1) , $array_1);
foreach ($array_2 as $item)
{
$result[$item[$key]] = isset($temp_array[$item[$key]]) ? array_merge($item, $temp_array[$item[$key]]) : $item;
}
return array_values(array_merge($result, array_diff_key($array_1, $result)));
}
$merged_arrays = array_merge_items_by_common_key_value('Key', $temp_array, $array_2);
First, a temporary array is created: it is equal to $array_1, but its keys are the values to be matched.
Then, $array_2 is looped. When a match is found, the merge is done. If there is no match, then the $array_2 value is maintained, untouched.
Finally, those values in the $array_1 which were not matched, are also appended to the resulting array.
So, no item of both $array_1 or $array_2 is lost, while the matched items are merged.
#radashk's solution will work if you can always guarantee that $array1[$i] corresponds to $array2[$i]. From my reading of the question, that's not guaranteed, but instead you want to make sure that $array1[$i]['Key'] == $array2[$j]['Key'], and combine elements where those Keys match.
There may be a more elegant solution, but I would do it like this:
// builds up new $tmpArray, using the Key as the index
$tmpArray = array();
foreach($array1 as $innerArray1){
$tmpArray[$innerArray1['Key']] = $innerArray1;
}
//Merges the values from $array2 into $tmpArray
foreach($array2 as $innerArray2) {
if (isset($tmpArray[$innerArray2['Key']])) {
$tmpArray[$innerArray2['Key']] = array_merge($tmpArray[$innerArray2['Key']], $innerArray2);
}else{
$tmpArray[$innerArray2['Key']] = $innerArray2;
}
}
Use temporary first level keys to swiftly identify matching Key values between the two arrays. When an array2 row qualifies for merger with the first, use the union-assignment operator (+=). Call array_value() after looping if you don't want to preserve the temporary keys.
Code: (Demo)
$result = array_column($array1, null, 'Key');
foreach ($array2 as $row) {
if (isset($result[$row['Key']])) {
$result[$row['Key']] += $row;
}
}
var_export(array_values($result));
I need help working with arrays. I have an array of data from a MySQL query. After printing it in a for loop, I get the following array_flip:
Array (
[Duru 60] => 0
[Maxwell 50] => 1
[Fashanu 70] => 2
[Nwankwo 80] => 3
[Obi 0] => 4
)
The array value is a combination of 2 fields name and total score. What I want to achieve is an array like so:
Array (
[Duru 60] => 60
[Maxwell 50] => 50
[Fashanu 70] => 70
[Nwankwo 80] => 80
[Obi 0] => 0
)
What I want to achieve is to change the default array numeric keys (0,1,2,3,4) to total score obtained from the query.
Here is the code that gave the first array block:
PHP code begins
$dataA = array();
foreach($data as $key => $val){
$dataC = $val['lastname']." ".$val['total'];
array_push($dataA,($dataC));
}
$dataD = (array_flip($dataA));
print_r($dataD);
$dataA = array();
foreach($data as $key => $val){
$dataK = $val['lastname']." ".$val['total'];
$dataV = $val['total'];
$dataA[$dataK] = $dataV;
}
print_r($dataA);
Try this:
$dataA = array();
foreach($data as $key => $val){
$dataC = $val['lastname']." ".$val['total'];
$dataA[$dataC] = $val['total'];
}
print_r($dataA);
Why can't you just do:
$newData = array();
foreach($data as $key => $val) {
$newData[$val['lastname'] . ' ' . $val['total']] = $val['total'];
}
print_r($newData);