我使用此代码搜索一对值&关键的多维数组
当lang为" en"
时,我需要提取对的值它适用于我,但我thibk不是PHP 7的好代码
$arr = [['lang' => null, 'title' => 'Main kaff'],
['lang' => 'en', 'title' => 'May way'],
['lang' => 'es', 'title' => 'Mi camino'],
['lang' => 'fr', 'title' => 'Mon chaimin']];
$key = "lang";
function multiSearch(array $array, array $pairs)
{
$found = array();
foreach ($array as $aKey => $aVal) {
$coincidences = 0;
foreach ($pairs as $pKey => $pVal) {
if (array_key_exists($pKey, $aVal) && $aVal[$pKey] == $pVal) {
$coincidences++;
}
}
if ($coincidences == count($pairs)) {
$found[$aKey] = $aVal;
}
}
return $found;
}
$x = multiSearch($arr, array('lang' => 'en'));
var_dump($x);
结果是正确的
array(1) {
[1]=>
array(2) {
["lang"]=>
string(2) "en"
["title"]=>
string(7) "May way"
}
}
答案 0 :(得分:2)
最简化的方式: -
<?php
$arr = [['lang' => null, 'title' => 'Main kaff'],
['lang' => 'en', 'title' => 'May way'],
['lang' => 'es', 'title' => 'Mi camino'],
['lang' => 'fr', 'title' => 'Mon chaimin']];
$lang= "en";
function multiSearch($arr,$lang)
{
return $arr[array_search($lang,array_column($arr,'lang'))];
}
$x = multiSearch($arr, $lang);
print_r($x);
输出: - https://eval.in/850435
详细阐述了发生了什么的方法: -
<?php
$arr = [['lang' => null, 'title' => 'Main kaff'],
['lang' => 'en', 'title' => 'May way'],
['lang' => 'es', 'title' => 'Mi camino'],
['lang' => 'fr', 'title' => 'Mon chaimin']];
$lang= "en";// language you want to search
function multiSearch($arr,$lang)
{
$array = array_column($arr,'lang'); // get lang-key all values as a single dimensional array from original multidimensional array
$key = array_search($lang,$array); // get key based on search-language-match from this single dimensional array
return $arr[$key]; // based on key return sub-array from original multi-dimensional array
}
$x = multiSearch($arr, $lang);// call function with original array and language you want to search
print_r($x); // print output
输出: - https://eval.in/850427
答案 1 :(得分:-1)
重新安排您的数据,一切都变得如此简单:
$arrTitle = [
null => 'Main kaff',
'en' => 'May way',
'es' => 'Mi camino',
'fr' => 'Mon chaimin'
];
echo $arrTitle[null] . "\n";
echo $arrTitle['en'] . "\n";
<强>结果:强>
主要卡夫
可能方式