PHP array_push多维关联数组保持结构 [英] PHP array_push multidimensional associative array to maintain structure
问题描述
我有一个数组:
$array= array(
'Book1' => array('http://www.google.com', '45' ),
'Book2' => array('http://www.yahoo.com', '46',
'Book3' => array('http://www.excite.com', '47', )
和我试图写一个函数,你可以搜索并与$键和$值不变返回数组。因此,如果有人在这里寻找第一册,第二册那么他们还是会回到一个数组:
and am trying to write a function where you can search and return an array with the $keys and $values intact. So if someone where to search "'Book1' , 'Book2' then they would get back an array :
$结果=阵列(第一册'=>阵列('http://www.google.com','45'),
第二册=>阵列(http://www.yahoo.com','46',))
这
$bookArray = array()
$bookDetailsarray = array();
$needles = array('book1' , 'book2' );
foreach ($needles as $needle) {
foreach ($array as $key => $value)
{
if ($key == $needle)
{
array_push($BookArray, $key);
array_push($bookDetailsarray, $value);
array_push($bookArray, $bookDetailsarray);
}
}
}
}
这工作,但在foreach的每次迭代它使加入$ bookDetailsaray到$值。因此,它返回:
This works, but on each iteration of the foreach it keeps adding the $bookDetailsaray to the $value. So it returns:
Book1 => [0]'Book1details'
Book2 => [0]'Book1details' [1]'Book2details'
Book3 => [0]'Book1details' [1]'Book2details' [2] 'Book3details'
等。
我希望能够做到:
array_push($BookArray, $key=>$value);
但很明显,那是不可能的。
有任何想法吗?即使它只是我需要什么阵列功能。
but obviously thats not possible. Any ideas? Even if its just what array function I need .
推荐答案
一个稍微更有效的方法使用基本的PHP函数,而不是循环做你的搜索:
A slightly more efficient method to do your search using basic PHP functions rather than looping:
$searchArray = array( 'Book1' => array('http://www.google.com', '45' ),
'Book2' => array('http://www.yahoo.com', '46'),
'Book3' => array('http://www.excite.com', '47' )
);
$needles = array('Book1','Book3');
$searchResults = array_intersect_key($searchArray,array_flip($needles));
var_dump($searchResults);
但是请注意,它是区分大小写
But note that it is case-sensitive
修改
如果你想不区分大小写的搜索,你可以使用 array_intersect_ukey()相反,使用自定义比较忽略按键的情况。
If you wanted a case-insensitive search, you could use array_intersect_ukey() instead, using a custom comparison to ignore the case of the keys.
function key_compare_func($key1, $key2) {
$key1 = strtoupper($key1);
$key2 = strtoupper($key2);
if ($key1 == $key2)
return 0;
else if ($key1) > $key2)
return 1;
else
return -1;
}
$searchResults = array_intersect_ukey($searchArray, array_flip($needles), 'key_compare_func');
编辑2
使用 strcasecmp()可以让用户自定义键比较简单了很多了。
Using strcasecmp() can make the user-defined key comparison a lot simpler too.
function key_compare_func($key1, $key2) {
return strcasecmp($key1,$key2);
}
这篇关于PHP array_push多维关联数组保持结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!