Reputation:
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] =>
)
Upvotes: -2
Views: 951
Reputation: 37
You should be able to remove empty array items with array_filter()
or do this:
$newArray = array_filter(array_map(function ($n) use ($rowView) {
if (substr($n, 0, 1) === '$' && !empty($rowView)) :
$k = substr($n, 1);
return $rowView[$k];
endif;
return $n;
}, $newFields));
Upvotes: 0