Gabriel I.
Gabriel I.

Reputation: 123

PHP: Associative array to numeric array

I have the following problem:

I have a 2-dimentional array containing some data, the first index contains the "year" and in the second has a range with values on it.

Here's an example of how a regular data is parsed though print_r().

Array
(
    [2017] => Array
        (
            [0] => 215
            [1] => 182
            [2] => 149
            [3] => 159
            [4] => 176
            [5] => 151
            [6] => 221
            [7] => 185
            [8] => 178
            [9] => 191
            [10] => 265
            [11] => 304
        )

    [2016] => Array
        (
            [0] => 162
            [1] => 179
            [2] => 162
            [3] => 201
            [4] => 169
            [5] => 148
            [6] => 139
            [7] => 139
            [8] => 149
            [9] => 187
            [10] => 264
            [11] => 229
        )
}

It works well in this case. I'm using json_encode() from PHP and JSON.parse() to send the array to JavaScript.

However, there's a particular case that's not working well enough.

[2015] => Array
    (
        [1] => 4
        [6] => 88
        [7] => 119
        [8] => 117
        [9] => 107
        [10] => 151
        [11] => 218
    )

This array is being interpreted as a associative array, so JavaScript interprets as an Object datatype. My external library expect an array so it throws an error and the JavaScript execution halts.

When I try to fill the missing data in between with zeroes with this method

foreach($eM_value as $key => $value)
{
    for($x = 0;$x <= 11;$x++)
        $eM_value[$key][$x] = ((isset($eM_value[$key][$x])) ? intval($eM_value[$key][$x]) : 0);
}

It still is interpreted as an associative array.

[2015] => Array
    (
        [1] => 4
        [6] => 88
        [7] => 119
        [8] => 117
        [9] => 107
        [10] => 151
        [11] => 218
        [0] => 0
        [2] => 0
        [3] => 0
        [4] => 0
        [5] => 0
    )

How can I convert this specific entry to a numeric array?

If more information is needed please comment and I'll add it.

Upvotes: 1

Views: 953

Answers (2)

Shridhar Sharma
Shridhar Sharma

Reputation: 2387

just use array_values function in PHP, it will output a numeric array of all the values

Upvotes: 2

Te Ko
Te Ko

Reputation: 768

You can use array_fill to prepare a placeholder array and then array_replace to put the real data in:

<?php

$input = [
    1 => 10,
    3 => 12,
    5 => 54
];

$output = array_replace(array_fill(0, 12, 0), $input);
print_r($output);

Will give you:

Array ( 
   [0] => 0 
   [1] => 10 
   [2] => 0 
   [3] => 12 
   [4] => 0 
   [5] => 54 
   [6] => 0 
   [7] => 0 
   [8] => 0 
   [9] => 0 
   [10] => 0 
   [11] => 0 
)

This way you can avoid sorting the keys.

Upvotes: 2

Related Questions