按值获取数组键 - 多维数组

时间:2014-09-15 09:50:39

标签: php arrays

我想通过一些数组的值获取/查找数组键。

我尝试了array_search,但这对我想要的多维数组没有帮助。

例如,我有这种数组,我需要将所有数组键都放在personal_code = 12345678910。在此示例中,我应该获得array(0,1),因为在第一个和第二个数组中是personal_code 12345678910

我怎么能得到这些钥匙?

Array
(
  [0] => Array
  (
    [id] => 32155
    [personal_code] => 12345678910
    [cadaster] => 12345:321:1234
    [purpose] => Purpose 1
    [address] => Blah blah 1
    [area] => 600m2
  )

  [1] => Array
  (
    [id] => 14131
    [personal_code] => 12345678910
    [cadaster] => 12345:123:4321
    [purpose] => Purpose 2
    [address] => Blah blah 3
    [area] => 1200m2
  )

  [2] => Array
  (
    [id] => 32303
    [personal_code] => 54321678910
    [cadaster] => 12345:123:1234
    [purpose] => Purpose 3
    [address] => Blah blah 2
    [area] => 1800m2
  )
)

2 个答案:

答案 0 :(得分:1)

您可以使用简单的foreach来获取这些密钥。例如:

$find = '12345678910';
$keys = array();
foreach($your_array as $key => $values) { // loop your array
    // now values will hold each array batch inside that parent array
    if($values['personal_code'] == $find) { // so it if matches
        $keys[] = $key; // then put it inside
    }
}

echo '<pre>';
print_r($keys);

Sample Demo

答案 1 :(得分:1)

$newArr = array();
foreach ($yourArr as $arr)
{
  if($arr['personal_code']==12345678910)
  {
    $newArr []=$arr;
  }
}
print_r($newArr);