【问题标题】:php array looping through two arrays with different indexesphp数组循环遍历具有不同索引的两个数组
【发布时间】:2018-11-07 08:14:04
【问题描述】:

我有两个数组,一个包含一个名称列表(数组名称 = 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];
    }
}

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

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

谢谢

【问题讨论】:

  • array_in - 你是说in_array
  • 您是否尝试过搜索$data 数组并检查$canNAMES
  • @Lithilion 是的,它不起作用

标签: php arrays loops


【解决方案1】:

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

$canNAMES = ["name 1","name 2","name 3"];

$data = json_decode ('[
{
    "agency": "test agency",
    "work_end": "21-Oct",
    "contractor": "name 3",
    "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 1",
    "rate": "£25.00",
    "hours": 30,
    "exp": null,
    "net": "£750.00",
    "vat": "£150.00",
    "gross": "£900.00"
}
]');

foreach ( $canNAMES as $name )  {
    foreach ( $data as $entry ) {
        if ( $name == $entry->contractor )    {
            print_r($entry);
        }
    }
}

【讨论】:

  • 我认为 use` in_array` 具有更好的可读性(如我的帖子中所示)——但它和这个一样......
【解决方案2】:

我猜你想要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;

【讨论】:

  • 这实际上是更好的方法,保存两次扫描。
猜你喜欢
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-10
  • 2022-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多