Wednesday, 29 August 2018

Convert a multidimensional array to a simple array

I am trying to convert a multidimensional array to a simple array. Some parts of my code is working, but I am lost when I have to preserve a child array. Here is the main array:

Array
(
    [0] => Array
        (
            [name] => scattr
            [value] => 250
        )

    [1] => Array
        (
            [name] => scattrtel
            [value] => 9830293789
        )

    [2] => Array
        (
            [name] => scattrcolor
            [value] => #2764C6
        )

    [3] => Array
        (
            [name] => scattrta
            [value] =>
        )

    [4] => Array
        (
            [name] => scattrcb
            [value] =>
        )

    [5] => Array
        (
            [name] => scattrmcb[1]
            [value] => 10
        )

    [6] => Array
        (
            [name] => scattrmcb[4]
            [value] => 40
        )

    [7] => Array
        (
            [name] => scattrmrdo
            [value] => 20
        )

    [8] => Array
        (
            [name] => scattrselect
            [value] => 30
        )

    [9] => Array
        (
            [name] => pwpus-shortcode-nonce
            [value] => 028c9426c5
        )

    [10] => Array
        (
            [name] => _wp_http_referer
            [value] => /wp-admin/admin-ajax.php
        )

)

And, my PHP to convert it in simple array:
$new = array();

foreach ( $datas as $data ) { // $datas as being the multidimensional array.
    $new[$data['name']] = $data['value'];
}

Now, a print_r of $new gives me:
Array
(
    [scattr] => 250
    [scattrtel] => 9830293789
    [scattrcolor] => #2764C6
    [scattrta] => gdkwsdghwkdhgk
    [scattrcb] =>
    [scattrmcb[1]] => 10
    [scattrmcb[4]] => 40
    [scattrmrdo] => 20
    [scattrselect] => 30
    [pwpus-shortcode-nonce] => 028c9426c5
    [_wp_http_referer] => /wp-admin/admin-ajax.php
)

So, I think my code is somewhat working, but not preserving that scattrmcb[1] and scattrmcb[4] in an array. Should give something like this:
[scattrmcb] => Array
            (
                [1] => 10
                [4] => 40
            )

How do I do that?
Thanks

So array_column() will get you most of the way. I used a regex to get the key and the inner array index and then eval() != evil:
foreach(array_column($datas, 'value', 'name') as $key => $value) {
    if(preg_match('/(.*)(\[\d+\])$/', $key, $match)) {
        eval("\$new['{$match[1]}']{$match[2]} = $value;");
    } else {
        $new[$key] = $value;
    }
}

Maybe a more or less readable eval():
        eval('$new["'.$match[1].'"]'.$match[2].' = $value;');

0 comments:

Post a Comment