I am making my own array from another one, using email field as key value. If there is more results with same email I am amking public ionViewWillEnter(): void {
this.appNav.swipeBackEnabled = true;
}
public ionViewDidLeave(): void {
this.appNav.swipeBackEnabled = false;
}
to existing key.
I am getting always data in my array (with email) and here is the example
Example data
array_push
$saved_data = [
0 => ['custom_product_email' => 'test@test.com',...],
1 => ['custom_product_email' => 'test@test.com',...],
2 => ['custom_product_email' => 'bla@test.com',...],
3 => ['custom_product_email' => 'bla@test.com',...],
...
];
I am getting error $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);
}
and if I debug my array, there is key with value of Undefined index: test@test.com
, so key is defined (!)
so 'test@test.com'
key is var $curVal
So the goal of foreach is to filter all objects in array with same email, here is the example:
undefined
答案 0 :(得分:2)
您没有看到错误消息吗?
解析错误:语法错误,意外' {'在.....从这段代码
$saved_data = [
0 => {'custom_product_email' => 'test@test.com',...},
1 => {'custom_product_email' => 'test@test.com',...},
2 => {'custom_product_email' => 'bla@test.com',...},
3 => {'custom_product_email' => 'bla@test.com',...},
...
];
将{}
更改为[]
以正确生成数组。
$saved_data = [
0 => ['custom_product_email' => 'test@test.com',...],
1 => ['custom_product_email' => 'test@test.com',...],
2 => ['custom_product_email' => 'bla@test.com',...],
3 => ['custom_product_email' => 'bla@test.com',...],
...
];
您的下一个问题在此代码中
$data = [];
foreach ($saved_data as $products) {
$curVal = $data[$products->custom_product_email];
// ^^^^^
$data
是一个空数组,您在上面初始化了2行,因此它不包含任何键或数据!
答案 1 :(得分:2)
这一行$curVal = $data[$products->custom_product_email];
没用,是引发错误的行:你刚刚将$ data初始化为空数组,逻辑上索引是未定义的。
您应该直接测试if (!isset($data[$products->custom_product_email])) {
然后解释:在未定义的数组索引的值和isset
中的相同代码之间存在根本区别。后者评估变量的存在,你可以放入一些不存在的东西(比如未定义的数组索引访问)。但是在测试之前你不能将它存储在一个变量中。
答案 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);
}