【问题标题】:Search array by value in key and get another key's value按键中的值搜索数组并获取另一个键的值
【发布时间】:2017-10-27 23:58:18
【问题描述】:

这是我的数组:

[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。如果我搜索“热狗”这个词,它将返回价格数量 3。我该怎么做?谢谢

【问题讨论】:

  • 请告诉我们您已经尝试过什么。
  • 使用类似的解决方案,将精确值匹配替换为pregmatchstrpos stackoverflow.com/questions/8102221/…
  • @GayanL 你能举个例子吗?谢谢
  • @JohnJaoill 我认为每个问题都有其重要性和价值,但在这里您应该先尝试一下,然后发布您尝试过的代码的帮助。
  • @JohnJaoill 上述评论中接受的答案,$product[$field] === $value 这一步需要更改strpos('burger', $product[$field]) > 0

标签: php arrays loops multidimensional-array


【解决方案1】:

您可以使用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>' ;
             }
            }
        }
    ?>
    

    【讨论】:

      【解决方案3】:

      这里我们使用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"];
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-18
        • 2023-03-28
        • 1970-01-01
        • 2012-01-15
        • 2019-09-20
        • 2012-06-02
        • 1970-01-01
        • 2021-09-30
        相关资源
        最近更新 更多