I'm using shuffle() to randomly generate items on my site like so:
shuffle($items);
$shirts = array();
foreach ($items as $key => &$row) {
$shirts[$row['Id']] = $row['shirts'];
}
The code goes further, but basically it's running a foreach and displays 12 results. However, shuffle() seems to only return the first 12 items in the array and shuffle them. The array may contain dozens of items, and I want to shuffle through the entire array. What am I doing wrong?
We need to see more code. As of right now according to the code, it should display every result (not just 12). This must mean that you're cutting the array down to 12 before you even shuffle it.
I just wrote this function to shuffle an array. It return the array shuffled so you can still keep the original array:
`function lowellshuffle($unshuff) {
$co = count($unshuff);
$m=0;
for ($i=0;$i<$co;$i++){
$p = rand(0,count($unshuff)-1);
$shuffled[$i] = $unshuff[$p];
for ($j=0;$j<count($unshuff);$j++){
if ($unshuff[$j] !== $shuffled[$i]){
$nq[$j- $m] = $unshuff[$j];
}
else {$m++;}
}
unset($unshuff);
$unshuff = $nq;
unset($nq);
$m=0;
}
return $shuffled;
}`
Related
in this foreach loop, i put a function returning the room quantity, each $sumqty['room_qty'] has different value, my question is, i want to get the highest value of $sumqty['room_qty'], do i put it in an array? how? any help will be appreciated.
<?php
foreach($reservation as $res){
$sumqty = sumqty($res['arrival'],$res['departure'],$res['room_id']);
$sumqty['room_qty'];
}
$highest = ???;
?>
i want to display the highest value by echo $highest
Yes, you can use an array. Provided $sumqty['room_qty'] is a numeric value the following will work:
$allquantities=array();
foreach($reservation as $res){
$sumqty = sumqty($res['arrival'],$res['departure'],$res['room_id']);
$allquantities[]=$sumqty['room_qty'];
}
$highest = max($allquantities);
Assuming that sumqty takes an 'arrival', 'departure' and 'room id' and returns an array with key 'room_qty' mapped to some integer:
<?php
$highest = -1000000000; //some really, really small number
foreach ($reservation as $res) {
$sumqty = sumqty($res['arrival'],$res['departure'],$res['room_id']);
if ($sumqty['room_qty'] > $highest) {
$highest = $sumqty['room_qty'];
}
}
echo $highest;
The general idea is that each time you find a higher value, you replace the previously highest value with the new higher value.
No extra array is necessary to accomplish this! Solutions that use an array to solve this problem are unnecessarily complicated. (edit: "complicated" is a poor choice of words; if an extra array is used than the program is slightly less efficient)
Get an array of all the values of $sumqty['room_qty'], $room_qty[] as in this case.
<?php
$room_qty = array();
foreach($reservation as $res){
$sumqty = sumqty($res['arrival'],$res['departure'],$res['room_id']);
$room_qty[] = $sumqty['room_qty'];
}
$highest = max($room_qty);
?>
Once you have the array you could use max() function to find the maximum value in the given array. Go through this manual you will get be clear about it.
If you have any array $p that you populated in a loop like so:
$p[] = array( "id"=>$id, "Name"=>$name);
What's the fastest way to search for John in the Name key, and if found, return the $p index? Is there a way other than looping through $p?
I have up to 5000 names to find in $p, and $p can also potentially contain 5000 rows. Currently I loop through $p looking for each name, and if found, parse it (and add it to another array), splice the row out of $p, and break 1, ready to start searching for the next of the 5000 names.
I was wondering if there if a faster way to get the index rather than looping through $p eg an isset type way?
Thanks for taking a look guys.
Okay so as I see this problem, you have unique ids, but the names may not be unique.
You could initialize the array as:
array($id=>$name);
And your searches can be like:
array_search($name,$arr);
This will work very well as native method of finding a needle in a haystack will have a better implementation than your own implementation.
e.g.
$id = 2;
$name= 'Sunny';
$arr = array($id=>$name);
echo array_search($name,$arr);
Echoes 2
The major advantage in this method would be code readability.
If you know that you are going to need to perform many of these types of search within the same request then you can create an index array from them. This will loop through the array once per index you need to create.
$piName = array();
foreach ($p as $k=>$v)
{
$piName[$v['Name']] = $k;
}
If you only need to perform one or two searches per page then consider moving the array into an external database, and creating the index there.
$index = 0;
$search_for = 'John';
$result = array_reduce($p, function($r, $v) use (&$index, $search_for) {
if($v['Name'] == $search_for) {
$r[] = $index;
}
++$index;
return $r;
});
$result will contain all the indices of elements in $p where the element with key Name had the value John. (This of course only works for an array that is indexed numerically beginning with 0 and has no “holes” in the index.)
Edit: Possibly even easier to just use array_filter, but that will not return the indices only, but all array element where Name equals John – but indices will be preserved:
$result2 = array_filter($p, function($elem) {
return $elem["Name"] == "John" ? true : false;
});
var_dump($result2);
What suits your needs better, resp. which one is maybe faster, is for you to figure out.
I am trying to prevent duplicates from occuring in a final array. I am trying to check for duplicates in a list of $media_candidate objects and compile them:
$iterator = 0;
// ensure items in final array are unique
while ((count($final_array) < $numResults) && ($iterator < count($media_data))) {
$media_candidate = $media_data[$iterator++];
if(!in_array($media_candidate['id'], $final_array)){
$final_array[] = $media_candidate;
}
}
As you can see in a print out of $final_array the last three elements are appearing 3 times with id, 343050519221992426_18478933. Any ideas as to what's going on?
First of all: You do not truncate the final array, so that all doublettes will end up at the end.
Second: You are reinventing the wheel: Read up on array_unique()
Edit
Third: After your edit, there is an even easier way:
$final_array=array();
foreach($media_data as $m) $final_array[$m['id']]=$m;
//You might want the next line or not
$final_array=array_values($final_array);
In essence you outsource the uniqueness to the hash keys of the array.
Try with:
if(!in_array($media_candidate['id'], $final_array)){
$final_array[] = $media_candidate['id'];
}
With $final_array[] you add new element at the end of the array.
You are checking $media_candidate['id'] but inserting $media_candidate in $final_array
Try array_unique function like this
$final_array = array_unique($media_candidate);
I have been trying to get this to work for a while now!
What I am trying to do is sort two arrays, so they both get ordered depending on the values inside one of the arrays. I don't know how to "attach" the arrays so both get ordered.
Here is my code:
$html = file_get_html('http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=hat&x=0&y=0');
$test = strtolower("Beechfield Turn-up Beanie");
$arrayT = array();
$arrayP = array();
foreach ($html->find('div.product') as $results) {
foreach ($results->find('a.title') as $title) {
$titleLow = strtolower($title->plaintext);
similar_text($test, $titleLow, $percent);
$arrayT[] = $title->plaintext;
$arrayP[] = round($percent);
}
}
I am comparing how similar the titles brought back from the outside website are to the variable $test, which in this case is just an example.
Next I want my output to be sorted depending on the $percent variables. For example with no sorting the output would be:
title-1 55
title-2 90
title-3 66
However I want it to be sorted:
title-2 90
title-3 66
title-1 55
I have tried using array_multisort however it would only sort each array independently. I have had a look at usort and ksort as well but couldn't get a working answer.
Any help would be appreciated! I have never used any kind of sorting in PHP and have only started learning arrays so please go easy on me.
I would suggest you to do this:
Instead of storing title and percentage in two different array.
you can have array indices as the titles.
Like this:
$html = file_get_html('http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=hat&x=0&y=0');
$test = strtolower("Beechfield Turn-up Beanie");
$arrayTP = array();
foreach ($html->find('div.product') as $results) {
foreach ($results->find('a.title') as $title) {
$titleLow = strtolower($title->plaintext);
similar_text($one, $titleLow, $percent);
$arrayTP[$title->plaintext] = round($percent);
}
}
You can sort it later using an array sort function based on the percentage. Use this: asort.
Because:
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
For printing do this:
foreach($arrayTP as $title => $percent ) {
.
.
.
How can you do this? My code seen here doesn't work
for($i=0;i<count($cond);$i++){
$cond[$i] = $cond[$i][0];
}
It can be as simple as this:
$array = array_map('reset', $array);
There could be problems if the source array isn't numerically index. Try this instead:
$destinationArray = array();
for ($sourceArray as $key=>$value) {
$destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
$array2[] = $item[0];
}
Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.
$array = $array2;
unset($array2); // Not needed, but helps with keeping memory down
Also, you might be able to, dependant on what is in the array, do something like.
$array = array_merge(array_values($array));
As previously stated, your code will not work properly in various situation.
Try to initialize your array with this values:
$cond = array(5=>array('4','3'),9=>array('3','4'));
A solution, to me better readable also is the following code:
//explain what to do to every single line of the 2d array
function reduceRowToFirstItem($x) { return $x[0]; }
// apply the trasnformation to the array
$a=array_map('reduceRowTofirstItem',$cond);
You can read the reference for array map for a thorough explanation.
You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.
function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
That should work. Why does it not work? what error message do you get?
This is the code I would use:
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
}