按键在值中搜索数组并获取另一个键的值

时间:2017-05-27 03:17:15

标签: php arrays loops multidimensional-array

这是我的数组:

[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
          )
  )

我想在所有数组中搜索,我想搜索单词" burger"。我想得到"汉堡"的价格和金额。这是5.如果我搜索单词" hotdog",它将返回价格金额3.我怎么能这样做?感谢

3 个答案:

答案 0 :(得分: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>' ;
         }
        }
    }
?>

答案 1 :(得分: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 :(得分: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"];
    }
}