How to convert array keys to all uppercase or lowercase?

Asked

Viewed 567 times

4

I’m getting some data from a Webservice, through a JSON response.

Convert this data from JSON to array, through json_decode. But one thing that’s bothering me is the fact the keys are coming with the name on Camelcase.

Something like this:

['Id' => 44, 'NumeroDoCliente' => 55, 'ProdutoCodigoNum' => 77]

My concern is that I once had a problem with the "excess of whim" (or disorganization, as you wish) on webservices where the data came in Camelcase. An example, id came as Id, and then "refactored" to ID, which caused a big problem for me, and stopped my system.

So I wanted to create a normalization of these indices, transforming them into upper case or Lower case.

Is there any way to change the "case" of the indexes in PHP? Is there any way to convert all the keys to upper case or Lower case?

1 answer

5


There is, the function array_change_key_case, Wallace. Veja:

$arr = ['Id' => 44, 'NumeroDoCliente' => 55, 'ProdutoCodigoNum' => 77];

To upper case:

$upperKeys = array_change_key_case($arr, CASE_UPPER);
print_r($upperKeys); // Array ( [ID] => 44 [NUMERODOCLIENTE] => 55 [PRODUTOCODIGONUM] => 77 )

To Lower case:

$lowerKeys = array_change_key_case($arr, CASE_LOWER);
print_r($lowerKeys); // Array ( [id] => 44 [numerodocliente] => 55 [produtocodigonum] => 77 )
  • Good. This saves part of my job +1

  • What’s missing? @Wallacemaxters

  • Finish processing the webservice data, kkkkkk. The rest leave with me here, thanks :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.