lundi 14 février 2022

Array random order to unique [closed]

I work with an APi in the form of Array. I do not own this APi and unfortunately cannot change how it is returned to me. The main problem with this API is that the order of the 'sensors' is randomly generated. That is, the content of sensors[0] can sometimes be in sensors[1] and vice versa.

This is a real problem, because if I do sensors[0]['key1'] to find my associated value, it can sometimes work. But other times key1 will be in sensors[1] or sensors[2] etc...

I tried a solution, see this topic: Add array to Value

but in fact I don't like it, because I break the structure of the API, which causes other problems later.

In short, while keeping the structure of the API, how to prevent this random order.

The name of the key is identifiable, but can be found randomly in several places. The values are unique.

<?php
$array1 = array(
    'sensors' => array(
        '0' => array(
                    'key1' => 'value1',
                    'key2' => 'value2',
                    'key3' => 'value3',
        ),
        '1' => array(
                    'key3' => 'value4',
                    'key4' => 'value5',
                    'key5' => 'value9',
        ),
        '2' => array(
                    'key1' => 'value13',
                    'key2' => 'value14',
                    'key3' => 'value15',
                    'key7' => 'value16',
                    'key8' => 'value17',
        ),
        '3' => array(
                    'key1' => 'value19',
                    'key7' => 'value20',
                    'key9' => 'value21',
        )
    )
);



$array2 = array(
    'sensors' => array(
        '0' => array(
                    'key1' => 'value1',
                    'key2' => 'value2',
                    'key3' => 'value3',
        ),
        '1' => array(
                    'key1' => 'value13',
                    'key2' => 'value14',
                    'key3' => 'value15',
                    'key7' => 'value16',
                    'key8' => 'value17',
        ),
        '2' => array(
                    'key1' => 'value19',
                    'key7' => 'value20',
                    'key9' => 'value21',
        ),
        '3' => array(
                    'key3' => 'value4',
                    'key4' => 'value5',
                    'key5' => 'value9',
        ),

    )
);

var_dump($array1['sensors'][0]['key1']); // value1 OK
var_dump($array1['sensors'][1]['key3']); // value4 OK
var_dump($array1['sensors'][3]['key1']); // value19 OK

var_dump($array2['sensors'][0]['key1']); // value1 OK 
var_dump($array2['sensors'][1]['key3']); // value15 OK but not same sensors
var_dump($array2['sensors'][3]['key1']); // WRONG

I think there are no solutions




Aucun commentaire:

Enregistrer un commentaire