[英]PHP: Check if array contains part of a value
我有 2 個 arrays:
$array_a = array(
array(
"id" => 1,
"merchant_reference" => "Ref 12345"
),
array(
"id" => 2,
"merchant_reference" => "Ref 67890"
),
array(
"id" => 3,
"merchant_reference" => "Ref 11122"
)
);
$array_b = array(
array(
"id" => 1,
"merchant_reference" => "12345"
),
array(
"id" => 2,
"merchant_reference" => "67890"
),
array(
"id" => 3,
"merchant_reference" => "11122"
)
);
而且,我試圖在“$array_b”中找到12345
,因為“$array_a”中的Ref 12345
包含“12345”。
我試過了:
$matches = array_filter($array_b, fn($item) => false !== strpos($item['merchant_reference'], $array_a[0]["merchant_reference"]));
if (!!$matches!== false) {
echo "Exists";
} else {
echo "Does not exist";
}
但是,這不起作用,因為我搜索的字符比 '$array_b' 中的字符多
您正在搜索包括“Ref”在內的完整文本。 使用正則表達式提取數字。
$matches = [];
preg_match('/Ref (\d+)/', $array_a[0]['merchant_reference'], $matches);
$searchRefNumber = $matches[1];
$matches = array_filter($array_b, fn($item) => $searchRefNumber === $item['merchant_reference']);
echo $matches ? 'Exists' : 'Does not exist';
印刷
Exists
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.