Find index of value in associative array in php? - php

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.

Related

Assign random but even amount from an array to a list array in PHP?

I have two arrays. One array $People currently creates number of 44 individuals. Lets just assume currently its
$People = array('1','2',...,'44');.
I have another array of 15 elements.
$Test = array('A','B',...'O');
Now I want to be able to assign the test randomly to each individual. I know how to do this using random function in php.
Where it has got tricky for me and what I need help with is how can I even out the test array. What I mean by this is since there are currently 44 individuals (this array will grow in future), what I want is 14 test versions to have 3 individuals and 1 version would have 2. So I want the test array to even out. I also want it to handle as growth of $People array.
Ex: Test Version D will have individual '4', '25'. Every other version has three random individuals.
Few ideas I came up with are things like running random integer on $Test array and which ever gets highest/lowest gets 2 individuals and rest three. This would give a problem when I increase the size of $People array; to deal with that I though about using modulus to figure out what will be even number of $Test beforehand.
I can do this and other ideas but am pretty sure there has to be a better way to do this.
Clarifying your situation:
You want to distribute the values inside $People randomly amongst your $Test array. The problem you stated you are having is that the amount of values in $People isn't always perfectly dividable by the amount of values in $Test, and you aren't sure how to go about implementing code to distribute the values evenly.
Proposed solution:
You could obtain the values in a foreach loop randomly 1 by 1 from a shuffled version of $People and put them in a new array called $Result. You would also have a conditional checking if you have extracted all the values from the shuffled $People array: if($count>=$arrayCount) where $arrayCount=$count($shuffledPeople);. If you have obtained all the values, you first make the $bool value false (in order not to iterate through the while loop anymore, and then you break; out of the foreach loop.
$Result =[];//the array containing the results
$shuffledPeople = $People;
shuffle($shuffledPeople);//mixing up the array
$arrayCount = count($shuffledPeople);//finding the total amount of people
$count = 0;
$bool = TRUE;
while ($bool)
{
foreach($Test as $value)
{
$Result[$value][] = $shuffledPeople[$count];
$count++;
if ($count>=$arrayCount)
{
$bool = FALSE;
break;
}
}
}
To view the results, all you would need to do is:
foreach ($Result as $key => $value)
{
echo "{$key}: <br>";
if (is_array($value))
{
foreach ($value as $something)
{
echo "-->{$something}<br>";
}
}
else
{
echo "-->{$value}<br>";
}
}
I believe that this is what you want to do...
Assume that you have $people and $test arrays. You want to know how many people per test...
$ppt = ceil(sizeof($people)/sizeof($test));
Now, $ppt is the people per test. The next step is to shuffle up the people so they are randomly assigned to the tests.
shuffle($people);
Now, we can chunk up the people into sub-arrays such that each sub-array is assigned to a test. Remember, the chunks are random now because we shuffled.
$chunks = array_chunk($people, $ppt);
Now, everyone in $chunks[0] will take $test[0]. Everyone in $chunks[1] will take $test[1]. Everyone in $chunks[2] will take $test[2].

Return duplicate values keys from array

I need to determine the keys of values, that have duplicates from an array.
What I came up with is:
$duplicates_keys = array();
$unique = array_unique($in);
$duplicates = array_diff_assoc($in, $unique);
foreach ($in as $key => $val){
if (in_array($val,$duplicates)){
$duplicates_keys[]=$key;
}
}
Which works, but that's pretty resource intensive, is there a faster way to do this?
As per my comment, i doubt this is a bottleneck. However you can reduce your iterations to once through the array, as follows:
$temp=[];
$dup=[];
foreach ($in as $key=>$val) {
if(isset($temp[$val])){
$dup[]=$key;
}else{
$temp[$val]=0;
}
}
Note that the value is set as an array key in temp, so you can use O(1) isset rather than in_array, which must search the full array until the value is found.
This is theoretically faster than your example, but you would need to profile it to be sure (as you should have already done to ascertain your current code is slow).
Probably you can do something else that has a far greater impact, like caching or a better database query
Use array_intersect() for this.
$duplicates_keys = array_intersect($in, $duplicates);
array_intersect()

Sorted Array of Objects

Is there any way to maintain a sorted array of objects?
For example, if I have an object with properties ID, Date, Name and a collection of these objects:
$col = array();
public function addNewObject($id, $date, $name)
{
$col[] = new Object($id, $date, $name);
//but instead of appending, it should place it by Name desc
}
If I call something like getObjects, it would return the items in the collection by Name desc.
I think there were some answers for getting objects back in a sorted order, but for efficiency, I would think it be better to sort at insert as the "sort by" variable in my case will never change.
UPDATE:
So based on the comments, I should resort the whole array each time something is added but that seems a bit memory intensive...
Since the array would always be in sorted order to start out with I can identify the location where I want to insert by traversing the array (would this be efficient, is there a better way?). Once I find that how could I "insert" a new object into the array?
I do not imagine that the array will be very large but I would like to implement this the most efficient way possible.
If you're not keen on resorting the array after you add (although I'd recommend it; realistically this wont be a performance issue and it keeps the code readable.
However, if you definitely don't want to do this then you can, as you said, traverse the array and find out where to insert:
$col = array();
public function addNewObject($id, $date, $name){
//Find the index to insert at
$index = 0;
foreach($col as $i => $item){
if($item->name > $name){
//This item is after the item we want to insert.
//Use the previous index and stop traversing
break;
}
$index = $i;
}
$col = array_splice($col, $index, 0, new Object($id, $date, $name));
}
Using array_splice to insert at an arbritary position thanks to https://stackoverflow.com/a/3797526/505722
this is a good example of a function that sorts an array from whatever key you want it sorted by
http://www.php.net/manual/en/function.sort.php#99419
in your example you should run it like :
array_sort($col, 'Name', SORT_DESC));
take in mind that every time you add a new item to the array the whole array is sorted each time

Match two arrays in a complicated way

I have two arrays of strings. The first array contains old data and the second array is new data that should overwrite the data in the old array. That's easily accomplished by matching up the indexes of the two arrays and overwriting any cells that are different.
However, the issue comes when the array of new data has a different length of indexes than the old one. For example if one new string is inserted into the middle of the new array, I don't want that index to overwrite the matching index in the old one.
Here is an example to illustrate what I'm trying to accomplish...
myoldarray("foobar", "blah", "zilch")
mynewarray("foobar", "blah", "watcha", "zilch")
My output should be
finalarray("foobar", "blah", "watcha", "zilch")
The order is important, however "zilch" needs to maintain the same key as before.
have you looked array_merge() from the php manual http://php.net/manual/en/function.array-merge.php
array_merge($myoldarray, $mynewarray);
If you necessarily have to keep the index, for numeric arrays you can use array_compare to get the difference and then add it at the same position of the array. In case this index already exists, we just move the old value & index 1 key higher. I hope that's what you want to do
$difference = array_diff($newarr,$oldarr);
foreach($difference as $diff)
{
foreach($newarr as $key => $value)
{
if($value == $diff)
{
if(array_key_exists($key,$oldarr))
{
$oldkey = count($oldarr)-1;
for($i=count($oldarr);$i>$key;$i--)
{
$oldarr[$oldkey+1] = $oldarr[$oldkey];
}
$oldarr[$key] = $value;
}
else
{
$oldarr[$key] = $value;
}
}
}
}
Good luck!

PHP multi-dimensional array find duplicates in specific dimensions

I have the following array:
$masterlist=[$companies][$fieldsofcompany][0][$number]
The third dimension only exists if the field selected from $fieldsofcompany = position 2 which contains the numbers array. Other positions contain regular variables. The 3rd dimension is always 0 (the numbers array) or Null. Position 4 contains numbers.
I want to cycle through all companies and remove from the $masterlist all companies which contain duplicate numbers.
My current implementation is this code:
for($i=0;$i<count($masterlist);$i++)
{
if($masterlist[$i][2][0][0] != null)
$id = $masterlist[$i][0];
for($j=0;$j<count($masterlist[$i][2][0]);$j++)
{
$number = $masterlist[$i][2][0][$j];
$query = "INSERT INTO numbers VALUES('$id','$number')";
mysql_query($query);
}
}
Which inserts numbers and associated IDs into a table. I then select unique numbers like so:
SELECT ID,number
FROM numbers
GROUP BY number
HAVING (COUNT(number)=1)
This strikes me as incredibly brain-dead. My question is what is the best way to do this? I'm not looking for code per se, but approaches to the problem. For those of you who have read this far, thank you.
For starters, you should prune the data before sticking it into the database.
Keep a look up table that keeps track of the 'number'.
If the number is not in the look up table then use it and mark it, otherwise if its in the look up table you can ignore it.
Using an array for the look up table and with keys being the 'number' you can use the isset function to test if the number has appeared before or not.
Example pseudo code:
if(!isset($lookupTable[$number])){
$lookupTable[$number]=1;
//...Insert into database...
}
Now that I think I understand what you really want, you might want to stick with your two-pass approach but skip the MySQL detour.
In the first pass, gather numbers and duplicate companies:
$duplicate_companies = array();
$number_map = array();
foreach ($masterlist as $index => $company)
{
if ($company[2][0][0] === null)
continue;
foreach ($company[2][0] as $number)
{
if (!isset($number_map[$number])
{
// We have not seen this number before, associate it
// with the first company index.
$number_map[$number] = $index;
}
else
{
// Both the current company and the one with the index stored
// in $number_map[$number] are duplicates.
$duplicate_companies[] = $index;
$duplicate_companies[] = $number_map[$number];
}
}
}
In the second pass, remove the duplicates we have found from the master list:
foreach (array_unique($duplicate_companies) as $index)
{
unset($masterlist[$index]);
}

Categories