简体   繁体   中英

Search array by value in key and get another key's value

here is my 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
          )
  )

i want to search in ALL arrays and I want to search for the word "burger". I want to get the price and amount of "burger" which is 5. If I search for the word "hotdog", it will return the price amount 3. How can i do that? thanks

If $array be your array. I Think It may Work.

<?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>' ;
         }
        }
    }
?>

You can use a foreach loop and then use strpos or stripos .

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;

Here we are using array_column , implode and preg_match .

1. array_column for retrieving specific column of an array

2. implode joins a array with a glue to make it string.

3. preg_match here for matching specific word in the given string.

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"];
    }
}
  1. Because you are searching for the first qualifying price only, it is best practice to use a conditional break to short circuit the loops. There is no reason to do more cycles if you have found a qualifying entry.

  2. Instantiate the $amount variable with a null value before the loop to properly distinguish between a successful search and an unsuccessful one.

  3. str_contain() is the modern function to case-sensitively search for a substring (PHP7.4 and higher). If you need case-insensitivity, you will need to use stripos($message['message'], $needle) == false . If you need to match whole words, you will need to call preg_match("/\b$needle\b/i", $message['message']) . If using regex and the $needle is coming from user input, you will need to apply escaping beforehand with $needle = preg_quote($needle, '/'); .

Code: ( Demo )

$needle = 'burger';

$amount = null;
foreach ($haystack as ['messages' => $messages, 'price' => $price]) {
    foreach ($messages as $message) {
        if (str_contains($message['message'], $needle)) {
            $amount = $price['amount'];
            break;
        }
    }
}
var_export($amount);
// 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM