Reputation:
I have a a vaery large array which is parsed to my php script in json form. I would like to convert the keys from string to integer. The keys are serial numbers so i can't just use array_values
. Currently i do it like this but would much prefer a solution that didn't involve a loop.
Example Array after json decode before int conversion:
array (
'123' => 'my text',
'223' => 'my text too',
'183' => 'my text foo',
'103' => 'my text doo',
// more array items
);
Example Code:
$data = json_decode($_POST['json']);
$newArr = Array();
foreach ($data as $key => $val) {
$ref = (int)$key;
newArr[$ref] = $key;
}
Upvotes: 0
Views: 309
Reputation: 71
If you have the source function via which the JSON encodes, just add
json_encode($data, JSON_NUMERIC_CHECK)
This will force the key fields in JSON to int (if int key field exist)
Upvotes: 0
Reputation: 2949
$arr = array (
'123' => 'my text',
'223' => 'my text too',
'183' => 'my text foo',
'103' => 'my text doo'
);
$newArray = array_combine(array_map('intval', array_keys($arr)), array_values($arr));
Upvotes: 4
Reputation: 461
Try this!
$test = array (
'123' => 'my text',
'223' => 'my text too',
'183' => 'my text foo',
'103' => 'my text doo',
// more array items
);
$newArr = array_combine(array_keys($test), array_keys($test));
:)
Upvotes: 0