2017-05-25 41 views
1

我有以下設置的數組:使用array_search在多維數組搜索

array(
array(
    'product_id' => 733 
), 
array(
    'product_name' => Example 
) 
) 

我要檢查733存在於我的數組,我需要使用array_search(通過谷歌搜索會)爲in_array沒有按在md陣列上工作。

我的代碼是:

$key = array_search('733', array_column($items, 'product_id')); 

如果我var_dump$items陣列我可以看到product_id

我想檢查數組中有特定的ID,然後執行其他代碼。

+1

嘗試此解決方案==> https://stackoverflow.com/a/6661561/1969866 – Narayan

+2

你可以這樣檢查: - https://eval.in/805046 –

+1

嘗試'array_values'函數https://www.w3schools.com/php/func_array_values.asp – aslantorret

回答

1

所以基本上你想檢查給定的product-id是否存在於你的多維數組中?

你可以像下面: -

<?php 

$items = array(
array(
    'product_id' => 733 
), 
array(
    'product_name' => Example 
) 
); 
function searchForId($id, $array) { 
    foreach ($array as $key => $val) { 
     if (!empty($val['product_id']) && $val['product_id'] == $id) { 
      return "true"; // or return key according to your wish 
     } 
    } 
    return "false"; 
} 
echo $found = searchForId(733, $items); 

輸出: - https://eval.in/805075

參考採取: - https://stackoverflow.com/a/6661561/4248328

+1

這似乎工作,謝謝 –

+0

@GarethGillman很高興幫助你。:) :) –

+1

正在等待最短時間通過,現在完成:) –