我认为这很简单,用两个键搜索多维数组以恢复第三个的值。当我开始无法让它工作时,我更加困惑。
Array (
[0] => Array ( [data] => Array ( [name] => Definite Position [Company_ID] => 4 [code] => DEF ) )
[1] => Array ( [data] => Array ( [name] => First Option [Company_ID] => 7 [code] => TNT ) )
[2] => Array ( [data] => Array ( [name] => Second Option [Company_ID] => 4 [code] => SEC ) )
[3] => Array ( [data] => Array ( [name] => Definite Out [Company_ID] => 6 [code] => DBO ) )
当[Company_ID]为4,[code]为'SEC'
时,我想带回[name]的值任何帮助将不胜感激。感谢
答案 0 :(得分:0)
这可能会有所帮助:
<?php
$array = array(
array(
"data" => array(
"name" => "Definite Position",
"Company_ID" => 4,
"code" => "DEF"
)
),
array(
"data" => array(
"name" => "First Option",
"Company_ID" => 7,
"code" => "TNT"
)
),
array(
"data" => array(
"name" => "Second Option",
"Company_ID" => 4,
"code" => "SEC"
)
),
array(
"data" => array(
"name" => "Definite Out",
"Company_ID" => 6,
"code" => "DBO"
)
)
);
/**
* Searches the array for matching criteria
*
* @param array $search Array of criteria to search for (eg. array("Company_ID" => 4, "code" => "SEC"))
* @param array $array The array to search
*
* @return array The elements of the array that matched the criteria
*/
function search($search, $array)
{
$retVal = array();
foreach($array as $k => $v)
{
$found = true;
foreach($search as $sKey => $sVal)
{
if ($v["data"][$sKey] != $sVal)
{
$found = false;
break;
}
}
if ($found)
$retVal[]= $v;
}
return $retVal;
}
$results = search(
array(
"Company_ID" => 4,
"code" => "SEC"
),
$array
);
var_dump($results);
结果:
array(1) {
[0]=>
array(1) {
["data"]=>
array(3) {
["name"]=>
string(13) "Second Option"
["Company_ID"]=>
int(4)
["code"]=>
string(3) "SEC"
}
}
}
答案 1 :(得分:0)
它只是一个访问data
索引的简单循环,然后是下面的索引:
$id = 4;
$code = 'SEC';
foreach($array as $values) {
if($values['data']['Company_ID'] == $id && $values['data']['code'] == $code) {
$result = $values['data']['name'];
break; // we found it no need to loop more
}
}