|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2006-09-08 20:03 UTC] z_rules55 at hotmail dot com
[2017-01-20 21:57 UTC] heiglandreas@php.net
-Status: Open
+Status: Feedback
-Package: Feature/Change Request
+Package: *General Issues
[2017-01-20 21:57 UTC] heiglandreas@php.net
[2017-01-29 04:22 UTC] php-bugs at lists dot php dot net
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Oct 26 05:00:01 2025 UTC |
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; } ?>