0

well this must a easy one but can't seem to figure it out I have this field range in an array that prints an id which repeats it self on array and would like to convert it to a sequence count starting from 0.

Live example: https://3v4l.org/Sf4nI#v7.0.33

Current output:

Array
(
    [0] => Array
        (
            [range] => 336
            [year] => 2020
            [month] => 222
        )

    [1] => Array
        (
            [range] => 336
            [year] => 2020
            [month] => 222
        )

    [2] => Array
        (
            [range] => 390
            [year] => 2020
            [month] => 222
        )

    [3] => Array
        (
            [range] => 390
            [year] => 2021
            [month] => 222
        )

)

Output I need:

Array
(
    [0] => Array
        (
            [range] => 0
            [year] => 2020
            [month] => 222
        )

    [1] => Array
        (
            [range] => 0
            [year] => 2020
            [month] => 222
        )

    [2] => Array
        (
            [range] => 1
            [year] => 2020
            [month] => 222
        )

    [3] => Array
        (
            [range] => 1
            [year] => 2021
            [month] => 222
        )

)

1 Answer 1

1

I think the simple solution here is to extract all range values from the array and remove the duplicated values, to make it start from 0 we will use array_values and flip it to can get the id by range value

$idList = array_flip(array_values(array_unique(array_column($array, 'range'))));

now you can get the id for any range you want like this

$idList[336];
// or 
$idList[390];

https://3v4l.org/kUa8D#v7.0.33

hope it's helpful

Sign up to request clarification or add additional context in comments.

2 Comments

not trying to remove duplicate, just trying to convert range IDs to sequence starting from 0
@Ered I edit the code to start from 0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.