这是我的数组:
[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.我怎么能这样做?感谢
答案 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
循环,然后使用strpos
或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;
答案 2 :(得分:2)
我们正在使用array_column
,implode
和preg_match
。
1。
array_column
,用于检索数组的特定列2.
implode
使用胶水连接数组以使其成为字符串。3。
preg_match
此处匹配给定字符串中的特定字词。
$toSearch="hotdog";
foreach($array as $key => $value)
{
if(preg_match("/\b$toSearch\b/",implode(",",array_column($value["messages"],"message"))))
{
echo $value["price"]["amount"];
}
}