简体   繁体   中英

Php array split based on array key name in

When I submit the form I get the output of array format like:

Array ( [quantity_2] => 2 [extra_2] => 1 [quantity_1] => 1 [quantity_3] => 5 [extra_3] => 1 )

I want to split this array based on array key last number like:

Array ( [quantity_2] => 2 [extra_2] => 1)
Array ( [quantity_1] => 1 [extra_2] => )
Array ( [quantity_3] => 5 [extra_3] => 1)

Many thanks for your valuable replay.

I dont think there is a way to create multiple arrays without doing it one by one, so the closest you could get IMO is following:

$arr = [
    'quantity_2' => 2,
    'extra_2' => 1,
    'quantity_1' => 1,
    'extra_1' => 10,
    'quantity_3' => 213,
    'extra_3' => 1
];

$newArray = [];
foreach ($arr as $key => $value) {
    $split = explode('_', $key);
    if (count($split) < 2) {
        continue;
    }

    $newArray[$split[1]][$split[0]] = $value;
}

print_r($newArray);

What it does: - create new empty array - loop over all elements - split the key by underscore and use the second part as id - fill the new array according to the format you want/might want - have new structured array which looks like a so:

Array
(
    [2] => Array
        (
            [quantity] => 2
            [extra] => 1
        )

    [1] => Array
        (
            [quantity] => 1
            [extra] => 10
        )

    [3] => Array
        (
            [quantity] => 213
            [extra] => 1
        )
)

I think this simple foreach will suits your needs.

$input = [
    'quantity_2' => 2,
    'extra_2' => 1,
    'quantity_1' => 1,
    'quantity_3' => 5,
    'extra_3' => 1
];

$output = [];

foreach ($input as $key => $value) {
    list ($name, $id) = explode('_', $key);
    $output[(int)$id][$key] = $value;
}

$output = array_values($output);

var_dump($output);

Made a fair few assumptions on this, and haven't added in any error checking but it should be enough to get you started.

Link to example code

$arr = [
    'quantity_1' => 1,
    'extra_1' => 1,
    'quantity_2' => 2,
    'extra_2' => 2,
    'quantity_3' => 3,
    'extra_3' => 3
];

$formatted = [];
$pattern   = '/_(\d)+$/';
$matches   = null;
foreach ($arr as $key => $value) {
    preg_match($pattern, $key, $matches);
    $formatted[$matches[1]][$key] = $value;
}

print_r($formatted);

Output:

Array
(
    [1] => Array
        (
            [quantity_1] => 1
            [extra_1] => 1
        )

    [2] => Array
        (
            [quantity_2] => 2
            [extra_2] => 2
        )

    [3] => Array
        (
            [quantity_3] => 3
            [extra_3] => 3
        )

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM