fastest way to get parent array key in multidimensional arrays with php - php

what is the best way to get parent array key with multidimensional arrays?
for example I have this array:
array(
[0] => array(0=> sample, 1=>picture, 2=>frame, 3=>google)
[1] => array(0=> iphone, 1=>orange, 2=>love, 3=>msn)
[2] => array(0=> joe, 1=>geee, 2=>panda, 3=>yahoo)
)
now I need to search for example google and get the parent array key..
which it should be 0...any ideas? I used for loop for this but I think it will be slow if I have arrays with 700000 rows..

If you have an array with 700,000 rows you are almost certainly doing something wrong... I would first recomend thinking about utilizing a different data store: flat file or some type of DB.
foreach($array as $key => $value) {
if(in_array('google', $value)) return $key
}

Arrays with 700,000 rows? How many arrays? 9/10 times problem is that you've got your data set up wrongly.
I'm going to go ahead and assume you're doing a search of some sort. As you can't index an array (in the search meaning of index) then you're probably best putting the data into a database and making the most of column indexing to search fast.
Depending on context, you may alternatively want to think about storing your data in files, one per array, and using file searches to find which file contains your value.

Related

array comparison vs SQL join

I have two, big, 2 dimensional arrays (pulled from some xml data) one (A list) is ~1000 items containing 5 fields the other (B list) is dinamically between 10.000-12.000 items containing 5 fields.
My idea was to compare EACH id key of list A against EACH id key of list B and on "true" compose a new array of combined fields, or just fields from array A if no match.
I used nested foreach loops and ended up with millions of iterations taking long time to process. needless to say...not a solution.
The form of this two structures and my needed result reminded me straight away of a sql join.
The questions are:
1.) Should i try sql or nested foreach might not be the best php way?
2.) Will a relational query be much faster than the iterations?
EDIT:
I pull data only periodically from an xml file (in a separate process) which contains 10+ fields for each node. Than i store the 5 fields i need in a CSV file to later compare with table A that i pull out from a mysql database. basically much like catalog update of attributes with fresh feed.
I'm affraid the original idea of storing into CSV was an error and i should just save the feed updates into a database too.
EDIT 2
The array list B look like this
Array
(
[0] => Array
(
[code] => HTS541010A9E680
[name] => HDD Mobile HGST Travelstar 5K100 (2.5", 1TB, 8MB, SATA III-600)
[price] => 385.21
[avail] => 0
[retail] => asbis
)
...
...
while the A list is similar in all but the 'code' field which is the only one useful for comparison
Array
(
[0] => Array
(
[code] => ASD-HTS541010A
[name] => HDD Mobile HGST Travelstar 5K100 (2.5", 1TB, 8MB, SATA III-600)
[price] => 385.21
[avail] => 0
[retail] => asbis
)
As you can see each feed will have universal code BUT some different random data as prefix or suffix so in each loop i have to do a couple of operations on the string to stripos or compare it to feeds id for a match or close match.
Pseudo code:
$mylist = loadfromDB();
$whslist = loadfromCSV();
foreach ($mylist as $myl) {
foreach ($whslist as $whl){
if ((stripos(code_a,code_b) OR (code_b,code_a) !== false)){
...
}
elseif (stripos(substr(strstr(code_a,'-'),1),code_b) !== false) {
...
}
elseif (stripos( substr(code_a,0,-5);) == !false ){
...
}
}
}
Using SQL will be faster because most SQL engines are optimized for joins, and your method is a brute-force method. However, inserting all that data to MySQL tables is quite a heavy task, so it's still not the best solution.
I suggest you do the join in PHP - but use a smarter algorithm. Start by sorting the two arrays by the field you want to match. Iterate both sorted arrays together - use two iterators(or pointers or indices or whatever) - lets say a iterates over A and b over B. On each iteration of the loop, compare the comparison field of the elements pointed by the a and b. If a's is smaller - advance a. If b's is smaller - advance b. If a's is equal to b's - you have a match, which you should store in a new list, and then advance both a and b(assuming the relation is one-to-one - if it's one-to-many you only advance the many iterator, and if it's many-to-many you need a bit more complex solution).

What is the order of foreach loop in PHP?

I have an array, for example
$arr=array(
"foo" => "fooval",
"boo" => "booval",
"roo" => "rooval",
);
and then I want to print all elements in pattern "key is value". This code should do the job:
foreach($arr as $key => $val)
echo $key." is ".$val;
Will I get this?
foo is fooval
boo is booval
roo is rooval
I mean the order. Is it guaranteed that it will execute in same order as the array was given, or the arrays are sorted somehow?
Thanks for any answers.
It will loop through the array in sequential order. So in your specific question you would see the results you expect.
arrays are ordered list of values and thier orders do not need to be sorted. It follows a sequence
FROM PHP DOC
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Mongo DB make an array with date as key?

Mongo make an array with date as key ?
[_id] => MongoId Object (
[$id] => 4fcf2f2313cfcd225700000d
)
[id] => 14
[name] => Aryan Roban
[news] => Array (
[08-06-2012] => 12
)
Here I want a make news as array with date as key and how to delete a particular key row ?
For example
I want to delete array element with key '08-06-2012' in news array , I dont know the value of it.
Finding Documents won't be a problem, this is very easy. Simply look if news has got a key which matches your search criteria:
db.foo.find({'news.08-06-2012': {'$exists': true}})
Don't forget to put an index on news.
But deleting them is not easily possible. There is another thread which show shows a way to do that, but it's really rather a workaround: In mongoDb, how do you remove an array element by its index Sadly this only works for arrays with numerical indexes and not for associative arrays.
Maybe you could use an own collection for news? Then you could update and delete them easily. Otherwise you could load a full document from your database, manipulate the news in your application and save it afterwards. This would require two datebase queries, but should work.
We can use like
db.foo.update({/*...*/}, {$unset: {'news.11-06-2012', 1}})

Are PHP Associative Arrays ordered?

I come from python background and the python datatype which is similar (a dictionary) is an unordered set of key value pairs.
I am wondering if PHP associative arrays are unordered? They appear to be ordered.
$test = array(
'test' => 'test',
'bar' => 'bar',
);
var_dump($test);
var_dump(array_slice($test, 0, 1));
Test always comes before bar and I can slice this array as you see. So is this always guaranteed to be ordered across php versions? Is the order just the order that I have declared the array with? So something is internally pointing 'test' to place [0] in the array? I have read http://php.net/manual/en/language.types.array.php but it doesn't shed too much light on this issue. I appreciate your responses. Ty
PHP associative arrays (as well as numeric arrays) are ordered, and PHP supplies various functions to deal with the array key ordering like ksort(), uksort(), and krsort()
Further, PHP allows you to declare arrays with numeric keys out of order:
$a = array(3 => 'three', 1 => 'one', 2 => 'two');
print_r($a);
Array
(
[3] => three
[1] => one
[2] => two
)
// Sort into numeric order
ksort($a);
print_r($a);
Array
(
[1] => one
[2] => two
[3] => three
)
From the documentation:
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
The documentation states:
An array in PHP is actually an ordered map.
So yes, they are always ordered. Arrays are implemented as a hash table.
From the php manual:
Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information.
I have relied on the fact that they are ordered and it has worked consistently in every project I've had.
The array is ordered but that does not mean the keys are sorted, it means that they are in a given order. Where the precise order is not specified, but it appears to be the order in which you introduced the key-value pairs in it.
To understand it, think what would it mean to not be ordered?
Well think to a relation in a relational database.
A relation is not intrinsically ordered: when you access it with a query the database, unless you provide an order clause, can return the same data in any order.
Even if the data was not modified the same data can be returned in different order.

How to access multi array value directly?

I have an array like array ( array 0 ('item1'=>1,'item2'=>3))....etc like so.
And I want to access say the value of item2 but I don't want to use array[0]['item2']...Is there another way to access it? I just need 1 value so I don't think putting it in a foreach loop would be efficient..
Any ideas?
You have two choices: if you know the row and column you want to access, then you can access it directly. If you don't know the row and column, then you'd need to use a foreach loop to find the item you want.
You can only access it directly if you know where it is.
Assuming you meant array ( 0 => array ('item1'=>1,'item2'=>3)), you can use
array_values() to renumber the top level values. Then you know that the first value ('item1'=>1,'item2'=>3) will be indexed by the key 0.

Categories