How can I manage some irregular array to regular array?

Viewed 59

I write code with some array that have different structure, but I must extract the data to do something else. How can I manager these array?

The array's structure are as follow:

$a = [
    'pos1' => 'somedata',
    'pos2' => ['data2', 'data3'],
    'pos3' => '';
];

$b = [
    [
        'pos1' => ['data1', 'data2', ['nest1', 'nest2']],
        'pos2' => ['data1', 'data2', 'data3'],
    ],
    ['data1', 'data2'],
    'data4',
];

The array's Index can be a key or a position, and the value of the corresponding index may be a array with the same structure. More tough problem is that the subarray can be nesting, and the time of the nesting has different length.

Fortunately, every array has it's owe fixed structure.

I want to convert the these array to the format as follow. When the index is a value, change it to the keyword; and if the index is a keyword, nothing changed.

$a = [
    'pos1' => 'somedata',
    'pos2' => [
        'pos2_1' => 'data2',
        'pos2_2' => 'data3'
    ],
    'pos3' => '';
];

$b = [
    'pos1' => [
        'pos1_1' => [
            'pos1_1_1' => 'data1', 
            'pos1_1_2' => 'data2', 
            'pos1_1_3' => [
                'pos1_1_3_1' => 'nest1', 
                'pos1_1_3_2' => 'nest2',
            ],
        ],
        'pos1_2' => [
            'pos1_2_1' => 'data1',
            'pos1_2_2' => 'data2',
            'pos1_2_3' => 'data3',
        ],
    ],
    'pos2' => ['data1', 'data2'],
    'pos3' => 'data4',
];

My first solution is for every array, write the function to convert the format(the keyword will specify in function). But it is a huge task and diffcult to manage.

The second solution is write a common function, with two argument: the source array and the configuration that specify the keyword to correspondent value index. For example:

$a = [0, ['pos10' => 1]];
$conf = [
    // It means that when the value index is 0, it will change it into 'pos1'
    'pos1' => 0, 
    'pos2' => 1,
];

The common funciton will generate the result of:

$result = [
    'pos1' => 0,
    'pos2' => ['pos10' => 1],
]

But this solution will lead to a problem: the config is diffcult to understand and design, and other people will spend a lot of time to understand the format after conversion.

Is there are some better solution to manage these array that other people can easy to use these array?

Thanks.

0 Answers
Related