为了账号安全,请及时绑定邮箱和手机立即绑定

PHP比较两个数组,但第一个数组的所有值都需要在第二个

PHP比较两个数组,但第一个数组的所有值都需要在第二个

PHP
白板的微信 2022-12-11 10:38:00
再次 - 抱歉过去的愚蠢解释......我没有得到我的错误,这让我发疯......所以我有两个数组——一个是普通数组,另一个是多维数组。但这也许无关紧要,因为我分解了两个要与数组进行比较的字符串...这是我的代码:<?php$arr1 = ["folds" => '01,03,'];if($arr1['folds'][strlen($arr1['folds'])-1] == ","){    $arr1['folds'] = substr($arr1['folds'], 0, -1);}$check = explode(",", $arr1['folds']);$arr2 = [    ["Offer" => "Website", "folds" => '01'],    ["Offer" => "Development", "folds" => '01,03,05,10,14,15,21,22,'],    ["Offer" => "Testing", "folds" => '01,03,04,10,15,22'],    ["Offer" => "Sales", "folds" => '01,03,10,22,']];$arr3 = [];foreach($arr2 as $i_arr){    if($i_arr['folds'][strlen($i_arr['folds'])-1] == ","){        $i_arr['folds'] = substr($i_arr['folds'], 0, -1);    }    $tocheck = explode(",", $i_arr['folds']);    foreach($check as $chk){        if(in_array($chk, $tocheck)){            $arr3[] = $i_arr;        }    }}print_r($arr3);?>所以我至少有两个数组($check 和 $tocheck)- $check 内容搜索或过滤值就像你想命名的那样。$tocheck 来自于数据库,得到要过滤的信息。我的代码没有按照我的意愿执行 - 因为 in_array($check[x], $tocheck[y]) 检查 $check 中的所有值和 $tocheck 中的所有值 - 但是当只有一个值适合时它说“真的”。我的挑战是当 $check 中的所有值也在 $tocheck 中时,只在 $arr3 中打印 $i_arr,而不是只打印一个...有人有想法吗?
查看完整描述

2 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

循环并$arr2检查strpos():$arr1["folds"]


<?php


$arr1 = ["folds" => '02,04'];


$arr2 = [

    ["Offer" => "Website", "folds" => '02'],

    ["Offer" => "Development", "folds" => '02,04,09']

];


$arr3 = [];

foreach($arr2 as $i_arr){

    if(isset($i_arr["folds"]) && strpos($i_arr["folds"], $arr1["folds"]) > -1){

        $arr3[] = $i_arr;

    }

}


print_r($arr3);


?>

输出:


Array

(

    [0] => Array

        (

            [Offer] => Development

            [folds] => 02,04,09

        )


)

https://paiza.io/projects/_0nC44WHlZJpkdLOjm1Tkw


查看完整回答
反对 回复 2022-12-11
?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

这里的解决方案 - 也许它会帮助别人:


<?php

// Your code here!

$arr1 = ["folds" => '01,03,'];

if($arr1['folds'][strlen($arr1['folds'])-1] == ","){

    $arr1['folds'] = substr($arr1['folds'], 0, -1);

}

$check = explode(",", $arr1['folds']);


$arr2 = [

    ["Offer" => "Website", "folds" => '03'],

    ["Offer" => "Development", "folds" => '01,03,05,10,14,15,21,22,'],

    ["Offer" => "Testing", "folds" => '01,03,04,10,15,22'],

    ["Offer" => "Sales", "folds" => '01,03,10,22,']

];

$use = "no";


$arr3 = [];

foreach($arr2 as $i_arr){

    if($i_arr['folds'][strlen($i_arr['folds'])-1] == ","){

        $i_arr['folds'] = substr($i_arr['folds'], 0, -1);

    }

    $tocheck = explode(",", $i_arr['folds']);

    foreach($check as $chk){

        if(in_array($chk, $tocheck)){

            $use = "yes";

        } else {

            $use = "no";

            break;

        }

    }

    if($use == "yes"){

        $arr3[] = $i_arr;

    }

}


print_r($arr3);


?>


查看完整回答
反对 回复 2022-12-11
  • 2 回答
  • 0 关注
  • 107 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信