0

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; 
}
1
  • Are you sure they are just integers? Commented Aug 13, 2015 at 9:02

3 Answers 3

4
$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));
Sign up to request clarification or add additional context in comments.

Comments

0

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));

:)

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.