【问题标题】:PHP - Search for value inside a multidimensional arrayPHP - 在多维数组中搜索值
【发布时间】:2017-07-23 20:44:20
【问题描述】:

我有一个多维$array。其中一列是customer name。 我必须将array 的所有行保存在一个数据库中,除了具有相同customer name 的行。

我编写了一个名为searchMultidimensionalArray 的函数,它创建了一个数组,其中包含具有不同customer name 的所有行。在数据库中插入一行之前,我在该数组中搜索当前行。如果存在,我什么也不做,否则我存储当前行。

这是我的解决方案,但它无法正常工作。

public function searchMultidimensionalArray($valueName, $arrayCustomer)
{
    foreach ($arrayCustomer as $key => $val) {
        if ($val['name'] === $valueName) {
            return true;
        }

        return false;
    }
}

这是我遍历数组的地方:

for ($i = 1; $i < $countArray; $i++) {
    $customer = new Customer();
    $customer->setName($customerName); // I already have $customerName data
    if ($i == 1) {

        $arrayCustomer[$i] = [
            'name' => $customerName,
        ];

        $em = $this->getDoctrine()->getManager();
        $em->persist($customer);
        $em->flush();

    }
    if ($this->searchMultidimensionalArray($customerName, $arrayCustomer) == true) {

        $repository = $this->getDoctrine()->getRepository('AppBundle:Customer');
        $customer = $repository->findOneBy(['name' => $customerName]);
    } else {
        $em = $this->getDoctrine()->getManager();
        $em->persist($customer);
        $em->flush();

        $arrayCustomer[$i] = [
            'name' => $customerName,
        ];
    }
}

【问题讨论】:

  • 问题出在哪里?
  • @Condorcho 具有相同'客户名称'的行都存储在数据库中

标签: php arrays oop multidimensional-array


【解决方案1】:

除非我误解了您的情况,否则可以通过多种方式有效地达到预期的结果。

  1. DB 方式:设置数据库表,使name 列成为唯一键。这样,如果您尝试 INSERT 重复,该行将根据需要失败。

  2. PHP方式:我会推荐array_column()array_unique()这样的:

    $unique_customer_names=array_unique(array_column($arrayCustomer,'customer_name'));
    

    然后使用$unique_customer_names 来识别重复项。

我希望这些选项之一为您提供更好的解决方案。

【讨论】:

    猜你喜欢
    • 2011-05-20
    • 2011-10-03
    • 1970-01-01
    • 2016-09-19
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多