note 109285 added to function.array-merge-recursive
| From: | robert dot schlak at alcatel-lucent dot com | Date: | Mon, 02 Jul 2012 16:40:01 +0000 |
| Subject: | note 109285 added to function.array-merge-recursive | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-189010@lists.php.net to get a copy of this message | ||
The presence of NULLs has been discussed in some earlier posts, but here is an example of the issue
and a fix. Although it may not be apparent, if using array_merge_recursive in a loop to combine
results from a database query or some other function, you can corrupt your result when NULLs are
present in the data. I discovered this when migrating from an Oracle DB to a MySQL DB. I had to
match the array structure returned from the PHP function calling the DB and got bit. The array_walk
call fixed this for me.
This is a simple example that lacks any DB calls and looping. Assume your array had the DB column
names (first, last, and age) and you needed to combine the data in a multi-dimensional array in
which the column name is an array key with all rows beneath it. The corruption occurs in $a3. If
using element position 2, one could create the fictitious 'pete johnson' because of the
collapsing of elements.
print "<pre>Show corruption\n";
$a1 = array('first'=>'bob', 'last'=>'jones',
'age'=>'48');
$a2 = array('first'=>'sam', 'last'=>'smith',
'age'=>'41');
$a3 = array('first'=>'pete', 'last'=>null,
'age'=>'3');
$a4 = array('first'=>'joe', 'last'=>'johnson',
'age'=>'33');
$a5 = array_merge_recursive($a1,$a2,$a3,$a4);
print_r($a5);
print "Show Fix\n";
$a1 = array('first'=>'bob', 'last'=>'jones',
'age'=>'48');
$a2 = array('first'=>'sam', 'last'=>'smith',
'age'=>'41');
$a3 = array('first'=>'pete', 'last'=>null,
'age'=>'3');
array_walk($a3, 'null_to_empty');
$a4 = array('first'=>'joe', 'last'=>'johnson',
'age'=>'33');
$a5 = array_merge_recursive($a1,$a2,$a3,$a4);
print_r($a5);
print "</pre>\n";
function null_to_empty(&$item) {
$item = is_null($item) ? '' : $item;
}
----
Server IP: 91.199.167.223
Probable Submitter: 135.245.10.5
----
Manual Page -- http://www.php.net/manual/en/function.array-merge-recursive.php
Edit -- https://master.php.net/note/edit/109285
Del: integrated -- https://master.php.net/note/delete/109285/integrated
Del: useless -- https://master.php.net/note/delete/109285/useless
Del: bad code -- https://master.php.net/note/delete/109285/bad+code
Del: spam -- https://master.php.net/note/delete/109285/spam
Del: non-english -- https://master.php.net/note/delete/109285/non-english
Del: in docs -- https://master.php.net/note/delete/109285/in+docs
Del: other reasons-- https://master.php.net/note/delete/109285
Reject -- https://master.php.net/note/reject/109285
Search -- https://master.php.net/manage/user-notes.php