2017-05-27 77 views
0

這裏是我的數組:搜索在鍵值陣列,並得到另一個關鍵的價值

[0] => Array 
    (
     [messages] => Array 
      (
       [0] => Array 
        (
         [message] => This is for sandwich 
       ) 
       [1] => Array 
        (
         [message] => This message is for burger 
       ) 

     ) 
     [price] => Array 
      (
       [amount] => 5 
       [currency] => USD 
     ) 

[1] => Array 
    (
     [messages] => Array 
      (
       [0] => Array 
        (
         [message] => This is a message for a delicious hotdog 
       ) 

     ) 
     [price] => Array 
      (
       [amount] => 3 
       [currency] => USD 
     ) 
) 

我想在所有的數組進行搜索,我想搜索的單詞「漢堡包」。我想要得到「漢堡包」的價格和數量是5。如果我搜索單詞「熱狗」,它將返回價格數量3.我該怎麼做?謝謝

+3

也請告訴我們你已經嘗試過。 –

+0

使用類似的解決方案,用'pregmatch'或'strpos'替換精確的值匹配https://stackoverflow.com/questions/8102221/php-multidimensional-array-searching-find-key-by-specific-value –

+0

@GayanL你能舉個例子嗎?謝謝 –

回答

2

您可以使用foreach循環,然後用strposstripos

foreach ($array as $row) { 
    foreach ($row['messages'] as $row2) { 
     if(strpos($row2['message'], 'burger') !== false) { 
      $stringFound = true; 
     } else { 
      $stringFound = false; 
     } 
    } 
    if($stringFound === true) { 
     $price = $row['price']['amount']; 
    } else { 
     $price = '0'; 
    } 
} 
echo $price; 
2

如果$array是你的數組。我認爲這可能會奏效。

<?php 
    $check = 'hotdog'; 

    foreach($array as $products){ 
     foreach($products['messages'] as $messages){ 
     if (strpos($messages['message'], $check) !== false) { 
      echo $check.' Found. Price'. $products['price']['amount'] .'</br>' ; 
     } 
     } 
    } 
?> 
2

這裏我們使用array_columnimplodepreg_match

1.array_column用於檢索數組

2.implode的特定列加入用膠水一陣列,使它字符串。

3.preg_match此處用於匹配給定字符串中的特定單詞。

Try this code snippet here

$toSearch="hotdog"; 

foreach($array as $key => $value) 
{ 
    if(preg_match("/\b$toSearch\b/",implode(",",array_column($value["messages"],"message")))) 
    { 
     echo $value["price"]["amount"]; 
    } 
} 
相關問題