php get most and least occurring values from Multidimensional arrays - php

I want to get most and least occuring values from php sequential/indexes, assoc and multidimensional arrays
Consider the following dataSet
$dataSet = [
'users' =>
[
'id' => 1,
'name' => "Alex",
'username' => 'alex',
],
[
'id' => 2,
'name' => "Alex",
'username' => 'alex'
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
]
];
Here above are samples dataSet
Here is what that i tried
function most_occurring(array $array, $key)
{
$dataSet = [];
$i = 0;
$keys = [];
foreach ($array as $k) {
if (in_array($k[$key], $keys)) {
$keys[$i] = $k[$key];
$dataSet[$i] = $k;
}
$i++;
}
return $dataSet;
}
I tried above code for most occurring values but not working at all, help me in most and least occuring values from arrays.
Thanks

Thanks to KIKO Software, you can still use array_count_values() for this cases. You will also need to use array_columns() and array_search() in this situation. You can refer to this link to see how array_search() helps in finding the maximum/minimum value and its corresponding key inside an array. To find the most or least occurrence, simply echo the last 6 variables that I have declared in the last 6 lines.
EDIT* reference:
unset
array_push
*And also, your first data in the assoc array is indexed 'user', but the second data in the assoc array is not indexed and hence it is indexed as 0.
$dataSet = [
'users' =>
[
'id' => 1,
'name' => "Alex",
'username' => 'alex',
],
[
'id' => 2,
'name' => "Alex",
'username' => 'alex'
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
]
];
$id = array_column($dataSet,'id');
$name = array_column($dataSet, 'name');
$username = array_column($dataSet, 'username');
$occur_id = array_count_values($id);
$occur_name = array_count_values($name);
$occur_username = array_count_values($username);
$most_occur_id = array_search(max($occur_id),$occur_id);
$most_occur_name = array_search(max($occur_name),$occur_name);
$most_occur_username = array_search(max($occur_username),$occur_username);
$least_occur_id = array_search(min($occur_id),$occur_id);
$least_occur_name = array_search(min($occur_name),$occur_name);
$least_occur_username = array_search(min($occur_username),$occur_username);
EDIT*: (In case of multiple highest occurence OR all same occurence, just add below code right below the above code.)
$flag = true;
$most_occur_name_list = [];
$count = 0;
while($flag)
{
$most_occur_name_ct = max($occur_name);
if($most_occur_name_ct == $count || $count == 0)
{
array_push($most_occur_name_list,array_search($most_occur_name_ct,$occur_name));
unset($occur_name[array_search($most_occur_name_ct,$occur_name)]);
$count = $most_occur_name_ct;
if(count($occur_name) == 0)
{
$flag = false;
break;
}
}
else
{
$most_occur_name_ct = $count;
$flag = false;
break;
}
}
//must reinitialize the array
$occur_name = array_count_values($name);
$flag = true;
$least_occur_name_list = [];
$count = 0;
while($flag)
{
$least_occur_name_ct = min($occur_name);
if($least_occur_name_ct == $count || $count == 0)
{
array_push($least_occur_name_list,array_search($least_occur_name_ct,$occur_name));
unset($occur_name[array_search($least_occur_name_ct,$occur_name)]);
$count = $least_occur_name_ct;
if(count($occur_name) == 0)
{
$flag = false;
break;
}
}
else
{
$least_occur_name_ct = $count;
$flag = false;
break;
}
}
if($most_occur_name_ct == $least_occur_name_ct)
{
$most_occur_name_list = [];
$least_occur_name_list = [];
}
echo "<pre>";
print_r($most_occur_name_list);

If you wanted to get a list of the min and max number of occurrences for just 1 element of the multidimensional array, then this code may offer a shorter method - comments in code...
$dataSet = [
'users' =>
[
'id' => 1,
'name' => "Alex",
'username' => 'alex',
],
[
'id' => 2,
'name' => "Alex",
'username' => 'alex'
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
],
[
'id' => 2,
'name' => "Paul Khot",
'username' => 'Paul',
]
];
// Create an array which has the username column, but retaining the keys from
// the original array
$set = array_combine(array_keys($dataSet),
array_column($dataSet, "username" ));
// Summarise the values
$count = array_count_values($set);
// Get a list of the keys which match the max and min values
$minRecords = array_keys($count,min($count));
$maxRecords = array_keys($count,max($count));
// Fetch the details for the maximum value (first one returned)
$maxElements = [];
foreach ( $maxRecords as $max ) {
$maxElements[] = $dataSet[array_search($max, $set )];
}
// Same for min values
$minElements = [];
foreach ( $minRecords as $min ) {
$minElements[] = $dataSet[array_search($min, $set )];
}
print_r($maxElements);
print_r($minElements);
With the test data I've added, you get the output...
Array
(
[0] => Array
(
[id] => 1
[name] => Alex
[username] => alex
)
[1] => Array
(
[id] => 2
[name] => Peter Khot
[username] => peter
)
)
Array
(
[0] => Array
(
[id] => 2
[name] => Paul Khot
[username] => Paul
)
)

Related

Matching multidimensional array value with two values from other array in php

I have array name $main_array
$main_array = [
[
'product_id' => '1',
'values' => '1"'
],
[
'product_id' => '4',
'values' => '1"'
],
[
'product_id' => '4',
'values' => 'blue'
],
[
'product_id' => '5',
'values' => 'blue'
]
];
I want to check values from other array
$check_array = [
'1"','blue'
];
Find product_id where 1" && blue both matching
Expected output ::
$output = [
[
'product_id' => '4',
'values' => '1"'
],
[
'product_id' => '4',
'values' => 'blue'
]
];
You could use an array to store matching elements using the product id as key.
$include = [] ;
foreach ($main_array as $key => $item) {
// if values match to $check_array
if (in_array($item['values'], $check_array)) {
// store using product id as key
$pid = $item['product_id'] ;
$include[$pid][] = $key;
}
}
// Filter to keep only items that match with all conditions
$include = array_filter($include, function($a) use ($check_array) {
return count($a) == count($check_array) ;
}) ;
$include = reset($include) ; // Get the first
// Recreate final array :
$out = [] ;
foreach ($include as $elem) {
$out[] = $main_array[$elem] ;
}
print_r($out);
Will outputs :
Array
(
[0] => Array
(
[product_id] => 4
[values] => 1"
)
[1] => Array
(
[product_id] => 4
[values] => blue
)
)
You may use nested foreach cycles. Supposed that $check_array containes two fields, you can write a code like this:
$output = array();
$match_array = array();
//check the first field correspondence
foreach ($main_array as $key1=>$sub_main) {
foreach ($sub_main as $key2=>$item) {
if ($check_array[0] == $item['values']) {
$match_array[] = $item['product_id'];
}
}
}
//try to match the second field
foreach ($main_array as $key1=>$sub_main) {
foreach ($sub_main as $key2=>$item) {
if ($check_array[1] == $item['values']) {
if (in_array($item['product_id'], $match_array) {
$output[] = array($item['product_id'], $check_array[1]);
$output[] = array($item['product_id'], $check_array[2]);
}
}
}
}

Group subarray data by one column and form comma-separated values from the secondary value in each group [duplicate]

This question already has answers here:
Group subarrays by one column, make comma-separated values from other column within groups
(2 answers)
Closed last month.
I have a two dimensional array which needs to be restructured. Rows must be grouped by date values, and within each group, the name values should be formed into a single comma-delimited string.
My input:
$missedFridgeLog = [
[
"date" => "01/01/18",
"name" => "Medicine"
],
[
"date" => "01/01/18",
"name" => "Drugs"
],
[
"date" => "02/01/18",
"name" => "Medicine"
],
[
"date" => "02/01/18",
"name" => "Drugs"
]
];
I have tried implementing a solution from Implode or join multidimentional array with comma, but it did not work as desired.
Desired output:
[
[
'date' => '01/01/18',
'name' => 'Medicine,Drugs',
],
[
'date' => '02/01/18',
'name' => 'Medicine,Drugs',
]
]
$missedFridgeLog = [
[
"date" => "01/01/18",
"name" => "Medicine"
],[
"date" => "01/01/18",
"name" => "Drugs"
]
[
"date" => "02/01/18",
"name" => "Medicine"
],
[
"date" => "02/01/18",
"name" => "Drugs"
]
];
$byDates = [];
foreach ($missedFridgeLog as $mfg) {
$byDates[$mfg['date']][] = $mfg['name'];
}
$res = [];
foreach ($byDates as $date => $name) {
$res[] = [
'name' => join(',',$name),
'date' => $date
];
}
var_dump($res);
You need to search key, value pair everytime you make a insert or update to result array. use this function() to search associate array. If match then update with additional name info else make a new insert to result array.
function filter_array($array){
///$array your previous array data
$result = array();
foreach($array["missedFridgeLog"] as $m){
$flag = true;
foreach($result as $k=>$r) {
if (is_in_array($r, "date", $m["date"]) == "yes") {
$result[$k]["name"] = $r["name"] . ',' . $m["name"];
$flag = false;
break;
}
}
if($flag==true){
$result[] = $m;
}
}
return array("missedFridgeLog"=>$result);
}
function is_in_array($array, $key, $key_value){
$within_array = 'no';
foreach( $array as $k=>$v ){
if( is_array($v) ){
$within_array = is_in_array($v, $key, $key_value);
if( $within_array == 'yes' ){
break;
}
} else {
if( $v == $key_value && $k == $key ){
$within_array = 'yes';
break;
}
}
}
return $within_array;
}
May be this is not the best way to do this, but it will help
$arr['missedFridgeLog'] = [
[
'date' => '01/01/18',
'name' => 'Medicine1'
],
[
'date' => '02/01/18',
'name' => 'New Medicine2'
],
[
'date' => '01/01/18',
'name' => 'Drugs1'
],
[
'date' => '02/01/18',
'name' => 'Medicine2'
],
[
'date' => '01/01/18',
'name' => 'New Drugs1'
],
[
'date' => '02/01/18',
'name' => 'Drugs2'
]
];
echo "<pre>";
$new_arr = array();
$date = array();
foreach ($arr['missedFridgeLog'] as $k => $a) {
if (in_array($a['date'], $date))
continue;
$new_arr[$k]['name'] = $a['name'];
$new_arr[$k]['date'] = "";
foreach ($arr[missedFridgeLog] as $key => $val) {
if ($key != $k) {
if ($a['date'] == $val['date']) {
$date[] = $new_arr[$k]['date'] = $a['date'];
$new_arr[$k]['name'] .= ", " . $val['name'];
}
}
}
if (empty($new_arr[$k]['date']))
unset($new_arr[$k]);
}
print_r($new_arr);
You can try below :-
Input array :-
$chkArray = [
'missedFridgeLog' => [
'0' => [
'date' => '01/01/18',
'name' => 'Medicine'
],
'1' => [
'date' => '01/01/18',
'name' => 'Drugs'
],
'2' => [
'date' => '02/01/18',
'name' => 'Medicine'
],
'3' => [
'date' => '02/01/18',
'name' => 'Drugs'
],
'4' => [
'date' => '02/01/18',
'name' => 'My Drugs'
]
]
];
$i = 0;
$finalarray = array();
foreach($chkArray['missedFridgeLog'] as $key=>$value) {
$checkExist = array_search($value['date'], array_column($finalarray, 'date'), true);
if($checkExist !== false) {
$finalarray[$checkExist]['name'] = $finalarray[$checkExist]['name'].','.$value['name'];
}
else {
$finalarray[$i]['date'] = $value['date'];
$finalarray[$i]['name'] = $value['name'];
$i++;
}
}
print_r($finalarray);
OutPut :-
Array
(
[0] => Array
(
[date] => 01/01/18
[name] => Medicine,Drugs
)
[1] => Array
(
[date] => 02/01/18
[name] => Medicine,Drugs,My Drugs
)
)
Do not use:
More than one loop,
Nested loops,
in_array(), or
array_search().
You only need one loop to apply temporary grouping keys. When a date/group is encountered after the first time, append its name value to the group's name value. When finished iterating, re-index the array.
Code: (Demo)
$result = [];
foreach ($missedFridgeLog as $row) {
if (!isset($result[$row['date']])) {
$result[$row['date']] = $row;
} else {
$result[$row['date']]['name'] .= ",{$row['name']}";
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'date' => '01/01/18',
'name' => 'Medicine,Drugs',
),
1 =>
array (
'date' => '02/01/18',
'name' => 'Medicine,Drugs',
),
)

Multidimensional Array delete duplicated key values with condition

I have an Array Like this:
$ratesData = [
1 => [
'id' => 1,
'amount' => 2
],
0 => [
'id' => 1,
'amount' => 1
],
2 => [
'id' => 1,
'amount' => 3
],
3 => [
'id' => 2,
'amount' => 2
]
];
I want to keep the duplicated id arrays with cheapest amount, the result will be like this:
[
0 => [
'id' => 1,
'amount' => 1
],
1 => [
'id' => 2,
'amount' => 2
]
]
I have a code that works with this problem, but I'm searching an elegant way to accomplish this without all this loops:
foreach($ratesData as $firstLoopKey => $firstLoopValue) {
foreach($ratesData as $secondLoopKey => $secondLoopValue) {
if($firstLoopValue['id'] === $secondLoopValue['id'] && $firstLoopKey != $secondLoopKey ) {
if ($ratesData[$secondLoopKey]['total_amount'] > $ratesData[$firstLoopKey]['total_amount']) {
$deleteElements[] = $secondLoopKey;
}
}
}
}
if (isset($deleteElements)) {
foreach ($deleteElements as $element) {
unset($ratesData[$element]);
}
}
$ratesData = array_values($ratesData);
return $ratesData;
You can sort by amount descending and then extract the array indexing by id which will eliminate the duplicates with the lowest amount overwriting the higher:
array_multisort(array_column($ratesData, 'amount'), SORT_DESC, $ratesData);
$ratesData = array_column($ratesData, null, 'id');
Yields:
Array
(
[1] => Array
(
[id] => 1
[amount] => 1
)
[2] => Array
(
[id] => 2
[amount] => 2
)
)
I always like having the key the same as a unique id to make array access/sorting easier, but you can re-index if needed:
$ratesData = array_values($ratesData);
Some simple solution:
// your source array
$ratesData = [];
// result array
$filtered = [];
foreach ($ratesData as $v) {
$id = $v['id'];
// if this is `$id`, which is not in `$filtered` yet
// or value of `$filtered[$id]['amount']` is greater then current `$v`
// then replace `$filtered[$id]` with current `$v`
if (!isset($filtered[$id]) || $filtered[$id]['amount'] > $v['amount']) {
$filtered[$id] = $v;
}
}
echo'<pre>',print_r(array_values($filtered)),'</pre>';
Another good solution
$uniqueRates = [];
foreach ($ratesData as $rateData) {
$key = $rateData['id'];
if (!\array_key_exists($key, $uniqueRates) ||
$rateData['total_amount'] < $uniqueRates[$key]['total_amount']
) {
$uniqueRates[$key] = $rateData;
}
}
return array_values($uniqueRates);

How do I reform this array into a differently structured array

I have an array that looks like this:
[0] => Array
(
[name] => typeOfMusic
[value] => this_music_choice
)
[1] => Array
(
[name] => myMusicChoice
[value] => 9
)
[2] => Array
(
[name] => myMusicChoice
[value] => 8
)
I would like to reform this into something with roughly the following structure:
Array(
"typeOfMusic" => "this_music_choice",
"myMusicChoice" => array(9, 8)
)
I have written the following but it doesn't work:
foreach($originalArray as $key => $value) {
if( !empty($return[$value["name"]]) ){
$return[$value["name"]][] = $value["value"];
} else {
$return[$value["name"]] = $value["value"];
}
}
return $return;
I've tried lots of different combinations to try and get this working. My original array could contain several sets of keys that need converting to arrays (i.e. it's not always going to be just "myMusicChoice" that needs converting to an array) ?
I'm getting nowhere with this and would appreciate a little help. Many thanks.
You just need to loop over the data and create a new array with the name/value. If you see a repeat name, then change the value into an array.
Something like this:
$return = array();
foreach($originalArray as $data){
if(!isset($return[$data['name']])){
// This is the first time we've seen this name,
// it's not in $return, so let's add it
$return[$data['name']] = $data['value'];
}
elseif(!is_array($return[$data['name']])){
// We've seen this key before, but it's not already an array
// let's convert it to an array
$return[$data['name']] = array($return[$data['name']], $data['value']);
}
else{
// We've seen this key before, so let's just add to the array
$return[$data['name']][] = $data['value'];
}
}
DEMO: https://eval.in/173852
Here's a clean solution, which uses array_reduce
$a = [
[
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
],
[
'name' => 'myMusicChoice',
'value' => 9
],
[
'name' => 'myMusicChoice',
'value' => 8
]
];
$r = array_reduce($a, function(&$array, $item){
// Has this key been initialized yet?
if (empty($array[$item['name']])) {
$array[$item['name']] = [];
}
$array[$item['name']][] = $item['value'];
return $array;
}, []);
$arr = array(
0 => array(
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
),
1 => array(
'name' => 'myMusicChoice',
'value' => 9
),
2 => array(
'name' => 'myMusicChoice',
'value' => 8
)
);
$newArr = array();
$name = 'name';
$value = 'value';
$x = 0;
foreach($arr as $row) {
if ($x == 0) {
$newArr[$row[$$name]] = $row[$$value];
} else {
if (! is_array($newArr[$row[$$name]])) {
$newArr[$row[$$name]] = array();
}
array_push($newArr[$row[$$name]], $row[$$value]);
}
$x++;
}

Map data from one multidimensional array to another based on shared id value

Here are two example of the format of the Arrays, full code and array content in my code below.
ARRAY 1
[
'version' => '1.0',
'injuries' => [
'timestamp' => 1377702112,
'week' => 1,
'injury' => [
[
'status' => 'Questionable',
'id' => '10009',
'details' => 'Shoulder'
],
[
'status' => 'Questionable',
'id' => '10012',
'details' => 'Ankle'
]
]
]
]
ARRAY 2
[
'version' => '1.0',
'players' => [
'timestamp' => 1377676937,
'player' => [
[
'position' => 'TMDL',
'name' => 'Bills, Buffalo',
'id' => '0251',
'team' => 'BUF'
],
[
'position' => 'TMDL',
'name' => 'Colts, Indianapolis',
'id' => '10009',
'team' => 'IND'
]
]
]
]
What I need to do is sort through both Arrays and finding matching values for the ID key. I need to then combine the values of both arrays into one array so I can print it out on screen. There is two API's provided, one for the injuries report with a player [id] key and the other for the Players Information with [id] keys. Here is how far I have gotten on this problem:
<?php
function injuries_report() {
//Get json files
$injuryData = file_get_contents('http://football.myfa...=1&callback=');
$playerData = file_get_contents('http://football.myfa...L=&W=&JSON=1');
//format json data into an array
$obj1 = json_decode($injuryData, true);
$obj2 = json_decode($playerData, true);
//return print_r($obj1); //print obj1 to see output
return print_r($obj2); //print obj2 to see output
}
?>
<!--get injuries report -->
<pre><?php injuries_report(); ?></pre>
Here's the working code, thanks to Chris:)
$injuryData = file_get_contents('http://football.myfantasyleague.com/2013/export?TYPE=injuries&L=&W=&JSON=1&callback=');
$array1 = json_decode($injuryData, true);
$playerData = file_get_contents('http://football.myfantasyleague.com/2013/export?TYPE=players&L=&W=&JSON=1');
$array2 = json_decode($playerData, true);
function map($x) {
global $array1;
if(isset($x['id'])) {
$id = $x['id'];
$valid = array_filter($array1['injuries']['injury'], create_function('$injury', 'return $injury["id"] == "' . $id .'";'));
if(count($valid) > 0) {
$x = array_merge($x, array_shift($valid));
}
}
return $x;
}
$output = array_map('map', $array2['players']['player']);
echo "<pre>";
print_r($output);
echo "</pre>";
Ok, I'm assuming you want to add injuries to players. The output will be the list of players, with the injuries added (where they apply)
$output = array_map(function($x) use ($array1) {
$id = $x['id'];
$valid = array_filter($array1['injuries']['injury'], function($injury) use ($id) {
return $injury['id'] == $id;
});
if(count($valid) > 0) {
$x = array_merge($x, $valid[0]);
}
return $x;
}, $array2['players']['player']);
print_r($output);
The output is this:
Array
(
[0] => Array
(
[position] => TMDL
[name] => Bills, Buffalo
[id] => 0251
[team] => BUF
)
[1] => Array
(
[position] => TMDL
[name] => Colts, Indianapolis
[id] => 10009
[team] => IND
[status] => Questionable
[details] => Shoulder
)
)
php 5.2
Edit The latest working version:
Oh you are using php 5.2. Here is a php 5.2 version, but it less pretty than the code before:
$injuryData = file_get_contents('http://football.myfantasyleague.com/2013/export?TYPE=injuries&L=&W=&JSON=1&callback=');
$array1 = json_decode($injuryData, true);
$playerData = file_get_contents('http://football.myfantasyleague.com/2013/export?TYPE=players&L=&W=&JSON=1');
$array2 = json_decode($playerData, true);
function map($x) {
global $array1;
if(isset($x['id'])) {
$id = $x['id'];
$valid = array_filter($array1['injuries']['injury'], create_function('$injury', 'return $injury["id"] == "' . $id .'";'));
if(count($valid) > 0) {
$x = array_merge($x, array_shift($valid));
}
}
return $x;
}
$output = array_map('map', $array2['players']['player']);
print_r($output);
The $array1 is global here. Check it here: http://pastebin.com/N3RqtfzN

Categories