Req #38684 [Opn->Fbk]: How about an array_key_walk_recursive() function?
Edit report at https://bugs.php.net/bug.php?id=38684&edit=1
ID: 38684
Updated by: heiglandreas@php.net
Reported by: z_rules55 at hotmail dot com
Summary: How about an array_key_walk_recursive() function?
-Status: Open
+Status: Feedback
Type: Feature/Change Request
-Package: Feature/Change Request
+Package: *General Issues
Operating System: WinXP
PHP Version: 5.1.6
Block user comment: N
Private report: N
New Comment:
Is this still relevant?
Previous Comments:
------------------------------------------------------------------------
[2006-09-08 20:03:54] z_rules55 at hotmail dot com
It's been a week since I submitted this, and it's still not assigned to anyone. Do I need
to include more information?
------------------------------------------------------------------------
[2006-09-01 20:45:17] z_rules55 at hotmail dot com
Description:
------------
While working recently on a project that involves JSON, I saw that it might be necessary to make
sure that a an array's keys are in utf-8 encoding for when I pass it to the JSON encoder, since
JSON expects stuff to be in utf-8. One possible way to do this with PHP's existing array
functions is with array_combine(), and converting all the elements in the keys array to utf-8 before
combining it with the elements array, but this seems like it could become more tedious with nested
arrays. I tried using foreach($array as &$key => $val) to convert the key's encoding in
each iteration, but got an error saying "Fatal error: Key element cannot be a reference".
So I wrote my own function (included below).
Why isn't there an array_key_walk_recursive() function, or something of the kind? A function
that would let you apply a callback to all keys in an array. Or, let you use foreach with a
referenced key as I mentioned.
Reproduce code:
---------------
<?php
function array_convert_key_encoding($array) {
$encoded_array = array();
foreach($array as $key => $val) {
if(is_string($key) && is_array($val)) {
$encoded_array[utf8_encode($key)] = array_convert_key_encoding($val);
}
else if(is_string($key)) {
$encoded_array[utf8_encode($key)] = $val;
}
else {
$encoded_array[$key] = $val;
}
}
return $encoded_array;
}
?>
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=38684&edit=1
Thread (4 messages)