2015-06-19 63 views
-1
Array ( 
     [0] => Array ( 
         [id] => 13137 
         [meta_value] => Chris 
         [field_id] => 104 
         [item_id] => 4413 
         [created_at] => 2015-06-17 17:00:21 
        ) 
     [1] => Array ( 
         [id] => 13136 
         [meta_value] => 0.10 
         [field_id] => 123 
         [item_id] => 4413 
         [created_at] => 2015-06-17 17:00:21 
        ) 
    ); 

如何訪問meta_value(Chris)where field_id = 104?如何使用PHP搜索多維數組中的值

回答

0

試試這個

foreach($array as $k => $v) { 
    if ($v['field_id'] ==104) { 
     $value = $v['meta_value']; 
    } 
} 

的print_r($值);

其中$數組中,你必須輸入的值可變,

3

。利用array_search功能

$key = array_search(104, array_column($array, 'field_id')); 
if($key !== false) 
{ 
     echo $array[$key]['meta_value']; 
} 

Demo

0

爲了確保代碼重用,你可以定義一個函數,如下所示:

<?php 
$array = [ 
    ['id' => 13137, 'meta_value' => 'Chris', 'field_id' => 104, 'item_id' => 4413, 'created_at' => '2015-06-17 17:00:21' ], 
    ['id' => 13136, 'meta_value' => 0.10, 'field_id' => 123, 'item_id' => 4413, 'created_at' => '2015-06-17 17:00:21' ], 
]; 

function getMetaValue($arr, $field_id) { 
    foreach($arr as $subArr) 
     if($subArr['field_id']==$field_id) 
      return $subArr['meta_value']; 
    return null; 
} 

echo getMetaValue($array, 104); // Chris 
echo getMetaValue($array, 123); // 0.10 
?>