I have
$data = array(
'user' => array(
'email' => 'user@example.com',
'name' => 'Super User',
'address' => array(
'billing' => 'Street 1',
'delivery' => 'Street 2'
)
),
'post' => 'Hello, World!'
);
I invoke method
$result = \Joomla\Utilities\ArrayHelper::flatten($data);
$result = array(
'user.email' => 'user@example.com',
'user.name' => 'Super User',
'user.address.billing' => 'Street 1',
'user.address.delivery' => 'Street 2',
'post' => 'Hello, World!'
);
Array
(
[user] => Array
(
[email] => user@example.com
[name] => Super User
[address] => Array
(
[billing] => Street 1
[delivery] => Street 2
)
)
[post] => Hello, World!
[email] => user@example.com
[name] => Super User
[address] => Array
(
[billing] => Street 1
[delivery] => Street 2
)
[user.email] => user@example.com
[user.name] => Super User
[billing] => Street 1
[delivery] => Street 2
[user.address.billing] => Street 1
[user.address.delivery] => Street 2
)
Php 7.2
This can be fixed as follows
public static function flatten($array, $separator = '.', $prefix = '')
{
$result = [];
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
} elseif (is_object($array)) {
$array = get_object_vars($array);
}
foreach ($array as $k => $v) {
$key = $prefix ? $prefix . $separator . $k : $k;
if (is_object($v) || is_array($v)) {
$result = array_merge($result, static::flatten($v, $separator, $key));
} else {
$result[$key] = $v;
}
}
return $result;
}
Labels |
Added:
?
|
Status | New | ⇒ | Information Required |
Category | ⇒ | Repository |
Status | Information Required | ⇒ | Closed |
Closed_Date | 0000-00-00 00:00:00 | ⇒ | 2018-10-17 23:07:56 |
Closed_By | ⇒ | mbabker |
This is already fixed in the 2.0 branch of the Utilities package, to be included in Joomla 4. Because fixing this results in a B/C break in the returned data, we're going to leave it this way. The test on the 2.0 branch for this method has been improved to test the full return result instead of only validating one key is correctly flattened.
Please submit this change as a pull request to https://github.com/joomla-framework/utilities (if I'm not mistaken the bug is that the flattened result gets assigned to the injected
$array
parameter and your fix is to assign the result to a new$result
parameter, right?).