php array index extraction
I created a array dynamic like:
$tmp = array ( array("name" > "rob"),
array("name" => "bla"));
Now i wand to search for the "index" in the array (with elemnt) Name = "rob"
like : give me the index for the array with the key "rob", the answer should be 0, the index for key "bla" sould be 1...
Is it possible to to this without开发者_开发知识库 a for or foreach function ? With a standard PHP function ?
thanks for the answer.
$index = array_search($key, array_map(function ($item) {
return $item['name'];
}, $tmp));
Requires PHP5.3
Or you can use array_keys()
(works in pre-5.3 too)
$indexs = array_keys($tmp, array('name' => $key));
$indexs
is an array now, because there can be of course more than one index with the value array('name' => $key)
within $tmp
You could run an array_map
on your array with a callback that examines each element and tests for the value you are looking for, though you'd still need to keep an internal pointer to the index you are currently processing, so I suggest going with the foreach
loop anyways.
Just use array_keys with optional search value.
array_keys($array, 'item_to_search_for')
You might be looking for: http://php.net/manual/en/function.array-map.php
The function array_keys :
http://php.net/manual/en/function.array-keys.php
has an additional optional parameter where you can specify the value to search by.
精彩评论