PHP Sort Ascending Keeping Identical Keys - php

I am working with a php associative array and i want to sort in ascending order on array key...But it is removing identical keys and keeping one key.
Here is my code
<?php
$num = [
100 => 75,
45 => 89,
120 => 101,
120 => 121,
120 => 11,
];
asort($num );
print_r($num);
But result is Array ( [120] => 11 [100] => 75 [45] => 89 )
I want the output is ascending manner Array ( [120] => 11 [100] => 75 [45] => 89 [120] => 121 [120] => 101)
I want to keep all 3 key value pair with the key 120. How can i do it?

What you want is not valid in PHP; arrays cannot have more than one value with the same key. One alternative would be to use a multi-dimensional array, for example:
$num = [
[100 => 75],
[45 => 89],
[120 => 101],
[120 => 121],
[120 => 11],
];
This can then be sorted with usort:
usort($num, function ($a, $b) { return reset($a) - reset($b); });
Output:
Array
(
[0] => Array
(
[120] => 11
)
[1] => Array
(
[100] => 75
)
[2] => Array
(
[45] => 89
)
[3] => Array
(
[120] => 101
)
[4] => Array
(
[120] => 121
)
)
Demo on 3v4l.org
You can work with this array using a foreach loop, for example:
foreach ($num as $arr) {
echo key($arr) . ' => ' . reset($arr) . PHP_EOL;
}
Output:
120 => 11
100 => 75
45 => 89
120 => 101
120 => 121
Demo on 3v4l.org

An array key is by definition of being a key, unique. You can not have multiple parts of data saved under the same key. In PHP the later values simply overwrite the previous ones.
From the Manual:
If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.
What you can do, is have that key full of sub-array of other values. This will require the method of creating your current data structure to be updated but could output something like:
So;
$num = [
100 => 75,
45 => 89,
120 => [ 0 => 101,
1 => 121,
2 => 11]
];
asort($num );
print_r($num);
I would give you an example of how to construct this but would like to have your own code to work from first.

Related

how to remove array value from array when value not same from both the value [duplicate]

This question already has answers here:
How to Remove value from an array using another array with multiple values?
(4 answers)
Closed 4 years ago.
I have two array, and i want to remove duplicate record from array2. i don't want to link_id 35 record in array 2 because link_id 35 record is present in array1 so it's not show in array2.
I tried with array_map and Unique methods but it's not working well because i think both the array doesn't have the same value.
$array1=
[0] => stdClass Object
(
[link_id] => 35
[link_name] => Test Listerine cool mint packets 3 pack
[alias] => aa
[link_desc] =>
[user_id] => 47
[link_hits] => 103
[link_votes] => 1
[link_rating] => 5.000000
[link_featured] => 0
[link_published] => 1
[link_approved] => 1
[link_template] =>
)
[1] => stdClass Object
(
[link_id] => 373
[link_name] => Test Subject Data Collection Fish Fresh Yellow Tail
[alias] => ba
[link_desc] =>
[user_id] => 47
[link_hits] => 198
[link_votes] => 8
[link_rating] => 2.875000
[link_featured] => 0
[link_published] => 1
[link_approved] => 1
[link_template] =>
)
$array2 =
[0] => stdClass Object
(
[link_id] => 35
[link_name] => Test Listerine cool mint packets 3 pack
[link_desc] =>
[lat] => 0.000000
[lng] => 0.000000
[contactperson] =>
[cat_name] => AA - Made in USA
[link_votes] => 1
[link_rating] => 5.000000
[link_featured] => 0
[value] => 30020864
)
[1] => stdClass Object
(
[link_id] => 541
[link_name] => Test Subject Data Collection Fish Fresh Yellow Tail
[link_desc] =>
[lat] => 25.182573
[lng] => -80.093079
[country] => United States
[postcode] => 33431
[contactperson] => Captain Jack Certified Charters
[cat_name] => BA - Product of USA
[link_votes] => 8
[link_rating] => 2.875000
[link_featured] => 0
[value] => NA
)
You can do that with array-filter. First extract all the ids from the first array and then filter the second array based of those ids.
$arr1 = array( (object) ["link_id"=> 35, "key" => "AAA"], (object) ["link_id"=> 373, "key" => "BBB"]);
$arr2 = array( (object) ["link_id"=> 35, "key" => "CCC"], (object) ["link_id"=> 341, "key" => "DDD"]);
$ids = array_column($arr1, "link_id");
$arr2 = array_filter($arr2, function ($e) use ($ids) {
return !in_array($e->link_id, $ids); //keep him in arr2 only if NOT in ids of arr1
});
Updated more fast answer Consider big amount of data (as for #mickmackusa comment) use this:
$ids = [];
foreach($arr1 as $e)
$ids[$e->link_id] = true;
$arr2 = array_filter($arr2, function ($e) use ($ids) {
return !isset($ids[$e->link_id]);
});
First solution is in O(n^2) and the second is in O(n)
This should do in php7.
Untested code:
var_export(array_diff_key(array_column($array2, null, 'link_id'), array_column($array1, null, 'link_id'));
Assign new 1st level keys to both arrays, then filter on those keys.
Checking against keys will be more efficient than making iterated calls of in_array.

How to find 5 biggest value from php array with original keys?

This array keys is a database primary keys and i need to find biggest value from array and after that update query which need this primary keys. so i need to it will be remain same keys.
My array
Array ( [1] => 7 [2] => 2 [3] => 2 [4] => 10 [5] => 15 [6] => 11 [7] => 40 )
i need this output
Array ( [7] => 40 [5] => 15 [6] => 11 [4] => 10 [1] => 7 )
The PHP arsort function will sort your array in descending order and maintain the indices.
$array = array ( 1 => 7, 2 => 2, 3 => 2, 4 => 10, 5 => 15, 6 => 11, 7 => 40 );
arsort($array);
print_r($array);
Demo: eval.in/836445https://3v4l.org/KQB5Y
To limit it to the top five use array_slice:
print_r(array_slice($array, 0, 5, true));
https://3v4l.org/DSkRt

Merge associative, multidimensional array php

I have a little Problem with a 2-dimensional and associative array which i need to merge in PHP.
So what i'm trying to achieve as output is something like this:
Array ( [0] => 6 [1] => 5 [2] => 9 [3] => 8 [4] => 3 [5] => 16 [6] => 55
[7] => 59 [8] => 56 [9] => 3 [10] => 4 .... [1293] => 2)
At the moment my output is as follows:
foreach ($arrayList as $key => $list) {
print_r($list);
}
is
Array ( [hgeneral1] => 6 [hgeneral2] => 5 [hgeneral3] => 9 [hgeneral4] => 8
[hgeneral5] => 3 [hgeneral6] => 16 [hmusic1] => 55 [hmusic2] => 59 [hmusic3] => 56 )
Array ( [hgeneral1] => 3 [hgeneral2] => 4 [hgeneral3] => 8 [hgeneral4] => 10 [hgeneral5]
=> 16 [hgeneral6] => 17 [hsport1] => 26 [hsport2] => 32 [hsport3] => 35 [hsport4] => 38
[hsport5] => 41 [hsport6] => 42 [hmusic1] => 55 [hmusic2] => 56 [hmusic3] => 58
[hmusic4] => 60 [hmusic5] => 61 ) Array ....
and like 50 more arrays.
Now since it's a associative array merge will just overwrite the values (if i understood that right), so my question is: Is there a way to get all these values into one big array?
I would really appreciate any help and sorry for my bad english (and the maybe kinda noobish question, but i'm really new to programming).
Cheers
Jutschge
"If the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended." array_merge doc
So take the values with array_values first and then merge like array_merge(array_values(arr1),array_values(arr2) .. )

Get keys of 5 bigests value from array

I have one problem. I must get 5 images which rates are the biggest. I have table which key = image_id and value = average rating.
Below is print_r of this array
Array ( ['5'] => 5.00 ['4'] => 3.05 ['12'] => 3.00 ['11'] => 4.00 ['21'] => 2.11 ['53'] => 4.44 )
For example
['5'] => 5.00
means that img which id = '5' have rating 5.00
Expected output 2 Arrays ($id and $rating)
Array ( [0] => '5' [1] => '53' [2] => '11' [3] => '4' [4] => '12' )
Array ( [0] => '5.00' [1] => '4.44' [2] => '4.00' [3] => '3.05' [4] => '3.00' )
Can you help me in this?
Use arsort(); and array_slice();
You can also avoid making 2 separate arrays with functions like array_keys(); and array_values();
// Original array
$array = array(
5 => 5.00,
4 => 3.05,
12 => 3.00,
11 => 4.00,
21 => 2.11,
53 => 4.44
);
// Sort array & maintain keys
arsort($array);
// Now get the first 5 elements, keeping the keys
$array = array_slice($array, 0, 5, true);
// IDs
print_r(array_keys($array));
// Ratings
print_r(array_values($array));
Have you tried to use arsort or uasort?

Counting rows/records in a multidimensional array

I have a set of nested arrays.
[data] is the top level array.
The lower level arrays are all identified by incremental numbers, dynamically assigned...essentially each sub-array identifies a row/record of information.
How would I extract the count of the sub-arrays? I need to be able to do this to post this data into a DB.
The number of sub-arrays is dynamic, and can change depending on what data I am parsing through.
[data] => Array
(
[0] => Array
(
[id] => 3475
[name] => Player1
[score] => 11870
[rank] => 213
[total_cities] => 2
[crown] => None
[alliance_id] => 134
[title] => Earl
[fame_total] => 509875
[fame_rank] => 381
[defeated_total] => 3436
[defeated_rank] => 376
[plunder_total] => 1388754
[plunder_rank] => 245
)
[1] => Array
(
[id] => 3523
[name] => Player2
[score] => 1978
[rank] => 281
[total_cities] => 1
[crown] => None
[alliance_id] => 134
[title] => Baron
[fame_total] => 0
[fame_rank] => 448
[defeated_total] => 0
[defeated_rank] => 448
[plunder_total] => 0
[plunder_rank] => 436
)
[2] => Array
(
[id] => 73
[name] => Player3
[score] => 1308
[rank] => 304
[total_cities] => 1
[crown] => None
[alliance_id] => 134
[title] => Marquess
[fame_total] => 5604153
[fame_rank] => 237
[defeated_total] => 37270
[defeated_rank] => 229
[plunder_total] => 68130
[plunder_rank] => 335
)
I used a combination of the methods highlighted by Marc B and Thanos to get my desired result
This is the code I used:
$count = 0;
foreach($data as $data=>$inner_array){
$count = $count+1;
}
echo $count;
I ran it with a test data set with 143 unique rows, and I got that echo back, so life is good.
Thanks guys.
Simplest method:
$count = 0;
foreach($mainarray as $subarray)
$count += count($subarray);
}
Let's assume $data is your main array:
This one prints the name of each inner array (0, 1, 2... for your example) and then counts each sub-array items:
echo "Number of sub-arrays: ".count($online_time); //optional
foreach($data as $inner_array=>$data_of_inner_array) {
echo $inner_array;
echo " --- ".count($data_of_inner_array);
echo "<br/>";
}
i assume output will be
Number of sub-arrays: 3
0 --- 14
1 --- 14
2 --- 14

Categories