Taffarel Xavier
Taffarel Xavier

Reputation: 532

How to slice array by key in php?

I would like to divide this array by the header key

$arr = [
      ["type" => "header"],
      ["type" => "input"],
      ["type" => "select"],
      ["type" => "header"],
      ["type" => "date"],
      ["type" => "number"],
      ["type" => "text"],
      ["type" => "header"],
      ["type" => "input"],
      ["type" => "input"],
      ["type" => "date"],
      ["type" => "paragraph 1"],
      ["type" => "paragraph 2"],
      ["type" => "paragraph 10546"],
    ];

Using this code, I get what I want, but it doesn't work since the array is dynamic.

print_r(array_slice($arr, 1, 2));
print_r(array_slice($arr, 4, 3));
print_r(array_slice($arr, 8, 10));

This is the code that I've tried so far but with no success:

$d = [];

    foreach ($arr as $key => $value) {
        if ($value['type'] == 'header') {
            $d[$key] = $value;
        }
    }

    $diff = array_filter($arr, function ($value) {
        return $value['type'] != "header";
    });

    $myArr = [];
    
    foreach (array_keys($d) as $key => $value) {
        $myArr[] = array_slice($diff, $value, $key + 2);
    }

Expected result:

Array
(
    [0] => Array
        (
            [type] => input
        )

    [1] => Array
        (
            [type] => select
        )

)

Array
(
    [0] => Array
        (
            [type] => date
        )

    [1] => Array
        (
            [type] => number
        )

    [2] => Array
        (
            [type] => text
        )

)

Array
(
    [0] => Array
        (
            [type] => input
        )

    [1] => Array
        (
            [type] => input
        )

    [2] => Array
        (
            [type] => date
        )

    [3] => Array
        (
            [type] => paragraph 1
        )

    [4] => Array
        (
            [type] => paragraph 2
        )

    [5] => Array
        (
            [type] => paragraph 10546
        )

)

Upvotes: 0

Views: 102

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

You can create an output buffer and loop over the input, each time you find a header value, then move on the output pointer so that it creates a new sub-array in the output...

$output = [];
$outputPointer = -1;
foreach ( $arr as $input )  {
    if ( $input['type'] === "header" )  {
        $outputPointer++;
    }
    else    {
        $output[$outputPointer][] = $input;
    }
}
print_r($output);

which gives (truncated)...

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [type] => input
                )

            [1] => Array
                (
                    [type] => select
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [type] => date
                )

            [1] => Array
                (
                    [type] => number
                )

Upvotes: 2

Related Questions