Php键未定义,但有关键

问题描述 投票:1回答:3

我使用电子邮件字段作为键值从另一个制作我自己的数组。如果有相同的电子邮件有更多的结果我正在使用array_push到现有密钥。

我总是在我的数组中获取数据(使用电子邮件),这是示例

输入数据

示例数据

$saved_data = [
    0 => ['custom_product_email' => '[email protected]',...],
    1 => ['custom_product_email' => '[email protected]',...],
    2 => ['custom_product_email' => '[email protected]',...],
    3 => ['custom_product_email' => '[email protected]',...],
    ...
];

$data = [];
foreach ($saved_data as $products) {
  $curVal = $data[$products->custom_product_email];
  if (!isset($curVal)) {
    $data[$products->custom_product_email] = [];
  }
  array_push($data[$products->custom_product_email], $products);
}

错误

我收到错误Undefined index: [email protected],如果我调试我的数组,有一个值为'[email protected]'的键,所以键定义(!)

所以var $curVal关键是undefined

结果

因此foreach的目标是使用相同的电子邮件过滤数组中的所有对象,以下是示例:

$data = [
  '[email protected]' => [
    0 => {data},
    1 => {data},
    ...
  ],
  '[email protected]' => [
    0 => {data},
    1 => {data},
    ...
  ],

];
php arrays undefined-index array-filter
3个回答
2
投票

这行$curVal = $data[$products->custom_product_email];是无用的,是引发错误的那个:你刚刚将$ data初始化为一个空数组,逻辑上索引是未定义的。

你应该直接测试if (!isset($data[$products->custom_product_email])) {

然后解释:在重新定义未定义的数组索引的值和isset中的相同代码之间存在根本区别。后者评估变量的存在,你可以放入一些不存在的东西(比如未定义的数组索引访问)。但是在测试之前你不能将它存储在变量中。


2
投票

你没有看到错误信息吗?

解析错误:语法错误,来自此代码的意外“{”.....

$saved_data = [
    0 => {'custom_product_email' => '[email protected]',...},
    1 => {'custom_product_email' => '[email protected]',...},
    2 => {'custom_product_email' => '[email protected]',...},
    3 => {'custom_product_email' => '[email protected]',...},
    ...
];

{}更改为[]以正确生成数组。

$saved_data = [
    0 => ['custom_product_email' => '[email protected]',...],
    1 => ['custom_product_email' => '[email protected]',...],
    2 => ['custom_product_email' => '[email protected]',...],
    3 => ['custom_product_email' => '[email protected]',...],
    ...
];

您的下一个问题是在此代码中

$data = [];
foreach ($saved_data as $products) {
  $curVal = $data[$products->custom_product_email];
//          ^^^^^

$data是一个空数组,您在上面初始化了2行,因此它不包含任何键或数据!


0
投票

检查$data[$products->custom_product_email]是否已在$data数组中设置

试试这段代码

$data = [];

foreach ($saved_data as $products) {
  $curVal = isset($data[$products->custom_product_email]) ? $data[$products->custom_product_email] : null;
  if (!isset($curVal)) {
    $data[$products->custom_product_email] = [];
  }
  array_push($data[$products->custom_product_email], $products);
}
© www.soinside.com 2019 - 2024. All rights reserved.