get only 5 elements from array - php

my array is setup as follow:
array
'testuri/abc' =>
array
'label' => string 'abc' (length=3)
'weight' => float 5
'testuri/abd' =>
array
'label' => string 'abd' (length=3)
'weight' => float 2
'testuri/dess' =>
array
'label' => string 'dess' (length=4)
'weight' => float 2
'testuri/gdm' =>
array
'label' => string 'gdm' (length=3)
'weight' => float 2
'testuri/abe' =>
array
'label' => string 'abe' (length=3)
'weight' => float 2
'testuri/esy' =>
array
'label' => string 'esy' (length=3)
'weight' => float 2
'testuri/rdx' =>
array
'label' => string 'rdx' (length=3)
'weight' => float 3
'testuri/tfc' =>
array
'label' => string 'tfc' (length=3)
'weight' => float 3
I want to get/filter the 5 elements with bigges 'weight'. Is there a php function to make this?
PS. My idea was to use foreach

Sort the array by the weight value in descending order and then get the first five values:
function cmpByWeight($a, $b) {
return $b['weight'] - $a['weight'];
}
uasort($array, 'cmpByWeight');
$firstFive = array_slice($array, 0, 5);

You'd be better using uasort with a callback that compares the 'weight' index of the passed values, and then array_slice to grab the first 5 elements (or last 5 depending on which way you sort...)

As far as I know there isn't.
You could use a heap for this, but for only 5 elements I'm not sure it's faster than just storing the top 5.

I would use array_multisort() and then grab the first 5 values.
array_multisort($weight, SORT_DESC, $label, SORT_ASC, $YOUR_ARRAY)
Then just grab $YOUR_ARRAY[0] - $YOUR_ARRAY[4] or iterate over the array to grab the first 5
[EDIT] here's a link to the function --> http://us3.php.net/manual/en/function.array-multisort.php

My English is not the best, i will try to explain, what i need. i can sort the array....but in the example above i have following:
1x weight 5
2x weight 3
5x weight 2
So...if I grab the first 5 elements, the another 3 with weight 2 will be ignored. So i need all 5 elements with weight 2....and so i have an array with 7 items.
Another example:
2x weight 5
4x weight 2
7x weight 1
All elements with weight1 must be ignored, So i get 6 elements in a new array..

Related

Comparing two arrays using both keys and values

Hello i have two arrays one coming from the client and the other coming from my database, i want to be able to compare these two arrays and make sure they are both equal.
By equal i mean they both have the same keys and the keys have the same values:
array (size=2)
0 =>
array (size=5)
'id' => int 13
'class' => string 'Regular' (length=7)
'price' => int 100
1 =>
array (size=5)
'id' => int 13
'class' => string 'Regular' (length=7)
'price' => int 200
array (size=2)
0 =>
array (size=5)
'id' => int 13
'class' => string 'Regular' (length=7)
'price' => int 100
1 =>
array (size=5)
'id' => int 13
'class' => string 'Regular' (length=7)
'price' => int 300
In the above scenario y function shuld return false because even though my arrays have the same number of elements the price property of the second index is different, first array has 200 ad second array has 300.
Also if for some reason array 1 has more elements than array 2 then it should also return false.
What would be the best way of doing this? Bets in terms of speed and performance.
I was thinking of converting both arrays to json and checking them like a string.
Try this
$arraysAreEqual = ($a == $b); // TRUE if $a and $b have the same key/value pairs.
$arraysAreEqual = ($a === $b); // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
array_diff() is there for this purpose. And its ok if the arrays are small, but for optimization, check out this post. It involves flipping the array value and key for faster comparison. And also this other stack comment for a hash table approach.

PHP find and return neighbor value in multidimensional array

I have a multidimensional array like so:
array (size=4)
0 =>
array (size=2)
'term' => string 'news-article' (length=12)
'count' => int 139
1 =>
array (size=2)
'term' => string 'industry-resource' (length=17)
'count' => int 37
2 =>
array (size=2)
'term' => string 'editorial' (length=9)
'count' => int 33
3 =>
array (size=2)
'term' => string 'bulletin' (length=8)
'count' => int 12
and I'm trying create a function that searches for a term and returns it's neighboring value, count.
My inclination was to use array_search(), however using this returns false, I'm guessin because it's only searching the first layer of the array (0,1,2,3).
I'm not so much looking for an exact answer but a nudge in the right direction. I'm guessing it will require looping through the array, but I do not know how to approach getting the neighboring count value once the term value is located. Any help is appreciated!
You can just loop through the array and access them directly.
$search_term = "news-article";
$count = 0;
foreach($array as $element) {
if($element['term'] == $search_term) {
$count = $element['count'];
break;
}
}

Count elements in simple array and order them by highest first

I have an array like the example below (from var_dump($tagged);:
array (size=1)
0 =>
array (size=7)
0 => string '#raining' (length=8)
1 => string '#raining' (length=8)
2 => string '#driving' (length=8)
3 => string '#hungrySoon' (length=11)
4 => string '#strangeworld' (length=13)
5 => string '#fruitweekFunky' (length=15)
6 => string '#kevins_rainbow_disco' (length=21)
7 => string '#raining' (length=8)
8 => string '#fruitweekFunky' (length=15)
I am simply after displaying the array as follows (From the most frequent first):
#raining
#fruitweekFunky
#driving ...etc
To achieve exactly what you've asked for (a descending ordered array of the highest occurences to the lowest) step by step:
Count the number of occurences:
$occurences = array_count_values($tagged[0]);
Sort the array (by value, because the number of occurrences is the current array value and the tag is the key - arsort() maintains the original keys):
arsort($occurences);
Get array of the keys for output (because the tags are currently keys):
var_dump(array_keys($occurences));
Fact is, $tagged is an array of arrays. So you need to take its first element.
Try :
$result = array_count_values(array_values($tagged[0]));
var_dump($result);

How to get colon delimited values from a string in php

I have a string
$style = "font-color:#000;font-weight:bold;background-color:#fff";
I need only
font-color
font-weight
background-color
I have tried
preg_match_all('/(?<names>[a-z\-]+:)/', $style, $matches);
var_dump($matches);
it gives me following output
array
0 =>
array
0 => string 'font-color:' (length=11)
1 => string 'font-weight:' (length=12)
2 => string 'background-color:' (length=17)
'names' =>
array
0 => string 'font-color:' (length=11)
1 => string 'font-weight:' (length=12)
2 => string 'background-color:' (length=17)
1 =>
array
0 => string 'font-color:' (length=11)
1 => string 'font-weight:' (length=12)
2 => string 'background-color:' (length=17)
There are three problems with this output
1. It is two or three dimensional array, I need one dimensional array.
2. It is repeating the information
3. It is appending ":" at the end of each element.
I need a single array like this
array
0 => 'font-color'
1 => 'font-weight'
2 => 'background-color'
Take out the colon:
$style = "font-color:#000;font-weight:bold;background-color:#fff";
preg_match_all('/(?<names>[a-z\-]+):/', $style, $matches);
var_dump($matches['names']);
Then use $matches['names'], since you named it, so you dont have redundant informations

Jagged Edge Arrays in PHP

I want to store some data in (I guess a semi-2, semi-3d array) in PHP (5.3)
What I need to do is store data about each floor like this:
Floor Num of Spots Handicap Motorcyle Other
1 100 array(15,16,17) array (47,62) array (99,100)
2 100 array(15,16,17) array (47,62) array (99,100)
and on
The problem is, is if the Handicap+Motorcyle+Other were ints, I could just store the data in a 2d array. However, they aren't. So I was thinking I could make something almost like a 3D array, with the first two columns only being in 2D.
The other thought I had was making a 2D array and for columns 3,4, and 5 instead of saving as
array(15,16)
//save like
1516
And then split at two digits (1 digit array numbers would be prefaced with a 0). However, I am wondering about the limit of the length of a string, because if I decide to move to a 3 digit length number in the array, like array(100, 104), and I need to store alot of numbers, I am thinking I am going to quickly exceed the max.
Edit 1
I like Omar's answer alot, but I'm not sure as to how to pull the data out.
While you could store them as ?D array, there is another approach you might want to consider :
$stuff = array (
'floor1' =>
array (
'NumSpots' => 100,
'handicap' => array (15,16,17),
'motorcycle' => array (47, 62),
'other' => array (99, 100),
),
),
'floor2' =>
'NumSpots' => 100,
'handicap' => array (15,16,17),
'motorcycle' => array (47, 62),
'other' => array (99, 100),
),
)
)
That way, you can access things through mroe meaningful names like
$stuff['floor1']['motorcycle'][2]
In php you can have named keys for your arrays. Each element in your array can have different types so you could have
$floors = array(
1 => array(
'num_spots' => 100,
'handicap' => array(15,16,17)
),
2 => array(
'num_spots' => 100,
'handicap' => array(15,16,17),
'motorcycle' => array (47,62)
)
);
etc...
You can do exactly that. Example:
$a = array();
$a[1] = array(
'spots' => 100,
'handicap' => array(5,3,5)
);
$a[2] = array(
'spots' => 50,
'handicap' => array(1,3,20)
);
var_dump($a);
Output:
array
1 =>
array
'spots' => int 100
'handicap' =>
array
0 => int 5
1 => int 3
2 => int 5
2 =>
array
'spots' => int 50
'handicap' =>
array
0 => int 1
1 => int 3
2 => int 20
You can use the array indices for the floor number or have a separate key/value for that.
Something like...
$floors = array();
$floors[1] => array(
Spaces => 100,
Handicapped => array(15, 16, 17),
Motorcycle => array(47, 62),
Other => array (1, 2, 3, ..., n)
)
You can then retrieve the values as ...
$Floor1Spaces = $floors[1]['Spaces']; //An integer
$Floor1HAndicapped = $floors[1]['Handicapped']; //A 1-dimensional array of integer

Categories