具有空数组的数组映射
在合并两个类似于下面的简化数组的数组时,其中一个数组有时最初是空的。
当页面打开时,$newFields
始终填充为来自数据库查询的数组,并与 $rowView
中的第二个值合并,但仅当页面上的条目具有已被打开。
问题是,当 $newFields 为空时, $rowView 的值出现在它的位置,这就是我试图阻止并使其没有值的情况。
// If entry not opened, initialize array
$rowView = is_array($rowView) ? $rowView : [];
$newArray = array_map(function ($n) use ($rowView) {
if (substr($n, 0, 1) === '$' && !empty($rowView)) :
$k = substr($n, 1);
return $rowView[$k];
endif;
return $n;
}, $newFields);
// Array $rowView is only when an entry has been opened
// otherwise it is empty
Array
(
[ID] => 2
[Marque] => MarqueName
)
// Array $newArray empty
Array
(
[0] => Marque
[1] => Marque
[2] =>
[3] => 1
[4] => 0
[5] => 50
[6] => 1
[7] =>
[8] =>
[9] => 0
[10] =>
)
// Array $newArray populated
Array
(
[0] => Marque
[1] => Marque
[2] => MarqueName
[3] => 1
[4] => 0
[5] => 50
[6] => 1
[7] =>
[8] =>
[9] => 0
[10] =>
)
In merging two arrays similar to the simplified ones below, one of them is sometimes initially empty.
$newFields
is always populated as an array from a database query when the page is opened and gets merged with the second value from $rowView
but only when an entry on the page has been opened.
The problem is, with $newFields empty, the value from $rowView appears in its place and that is what I am trying to stop and make it have no value instead.
// If entry not opened, initialize array
$rowView = is_array($rowView) ? $rowView : [];
$newArray = array_map(function ($n) use ($rowView) {
if (substr($n, 0, 1) === '
&& !empty($rowView)) :
$k = substr($n, 1);
return $rowView[$k];
endif;
return $n;
}, $newFields);
// Array $rowView is only when an entry has been opened
// otherwise it is empty
Array
(
[ID] => 2
[Marque] => MarqueName
)
// Array $newArray empty
Array
(
[0] => Marque
[1] => Marque
[2] =>
[3] => 1
[4] => 0
[5] => 50
[6] => 1
[7] =>
[8] =>
[9] => 0
[10] =>
)
// Array $newArray populated
Array
(
[0] => Marque
[1] => Marque
[2] => MarqueName
[3] => 1
[4] => 0
[5] => 50
[6] => 1
[7] =>
[8] =>
[9] => 0
[10] =>
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该能够删除空数组项
array_filter()
或执行以下操作:
You should be able to remove empty array items with
array_filter()
or do this: