php数组遍历具有不同索引的两个数组

时间:2018-11-07 08:14:05

标签: php arrays loops

我有两个数组,一个包含一个名称列表(数组名称= canNAMES),

["name 1","name 2","name 3"];

第一个数组中包含大约70个值,而我的第二个数组中包含大约600个对象(数组名称= {data),

[
{
    "agency": "test agency",
    "work_end": "21-Oct",
    "contractor": "name n",
    "rate": "£30.00",
    "hours": 32,
    "exp": null,
    "net": "£960.00",
    "vat": "£192.00",
    "gross": "£1,152.00"
},
{
    "agency": "test agency",
    "work_end": "21-Oct",
    "contractor": "name n",
    "rate": "£25.00",
    "hours": 30,
    "exp": null,
    "net": "£750.00",
    "vat": "£150.00",
    "gross": "£900.00"
}
]

我正在尝试使用php in_array函数来获取具有第一个数组中列出的名称的对象。

当我按以下方式使用它时,我可以获得所需的结果,但它最多只能读取70条记录

foreach ($canNAMES as $index => $row) {
    if (in_array($row, (array) $data[$index]["contractor"])) {
        $MAIN[] = $data[$index];
    }
}

上面的代码是我遍历具有70条记录的第一个数组(canNAMES数组)的地方。当我尝试遍历第二个数组(数据数组)时,由于第一个数组的索引不超过69,我得到了未定义的偏移量错误。

我的问题是如何解决此问题,是否有更好的方法来做我正在尝试的事情。

谢谢

2 个答案:

答案 0 :(得分:1)

如果名称不是唯一的,那么您可以轻松地遍历每组匹配另一组的数据...

hasAuthority(String authority)

答案 1 :(得分:1)

我想您希望data数组中所有具有canNAMES数组中存在的名称的元素。

请考虑以下内容:

$canNAMES = ["ccc","bbb","eee"];
$data = json_decode('[{"id":1, "contractor": "aaa"}, {"id":2, "contractor": "ddd"}, {"id":3, "contractor": "ccc"}, {"id":4, "contractor": "bbb"}]');
$res = array();

foreach($data as $elem) {
    if (in_array($elem->contractor, $canNAMES))
        $res[] = $elem;
}

echo print_r($res);
return;
相关问题