Home > Net >  filter associative array that has another array inside it
filter associative array that has another array inside it

Time:10-05

I have this $data, which holds an array of records from schedules table.

If you want to see the code, please check this repository from LaravelDaily, it's the same code I'm working on.

"07:00 AM - 07:05 AM" => array:5 [▼
  0 => 1
  1 => 1
  2 => 1
  3 => 1
  4 => 1
]
"07:05 AM - 07:10 AM" => array:5 [▼
  0 => 1
  1 => 1
  2 => 1
  3 => 1
  4 => 1
]
"07:10 AM - 07:15 AM" => array:5 [▼
  0 => 1
  1 => 1
  2 => 1
  3 => 1
  4 => 1
]
"07:15 AM - 07:20 AM" => array:5 [▼
  0 => 1
  1 => 1
  2 => array:3 [▼
    "schedule_id" => 10
    "time" => "07:15 AM - 07:20 AM"
    "subject_name" => "Subject Abc"
  ]
  3 => 1
  4 => 1
]

I want to only return/show the array that has another array inside it and remove the others like what you will see below.

In this case it's 07:15 AM - 07:20 AM

"07:15 AM - 07:20 AM" => array:5 [▼
  0 => 1
  1 => 1
  2 => array:3 [▼
    "schedule_id" => 10
    "time" => "07:15 AM - 07:20 AM"
    "subject_name" => "Subject Abc"
  ]
  3 => 1
  4 => 1
]

Is that possible without using a foreach loop?

What I use:

Laravel 9.33

PHP 8.1

CodePudding user response:

You can use array_filter by a custom callback function.

$list = [
    "07:00 AM - 07:05 AM" => [
        0 => 1,
        1 => 1,
        2 => 1,
        3 => 1,
        4 => 1,
    ],
    "07:05 AM - 07:10 AM" => [
        0 => 1,
        1 => 1,
        2 => 1,
        3 => 1,
        4 => 1,
    ],
    "07:10 AM - 07:15 AM" => [
        0 => 1,
        1 => 1,
        2 => 1,
        3 => 1,
        4 => 1,
    ],
    "07:15 AM - 07:20 AM" => [
        0 => 1,
        1 => 1,
        2 => [
            "schedule_id"  => 10,
            "time"         => "07:15 AM - 07:20 AM",
            "subject_name" => "Subject Abc",
        ],
        3 => 1,
        4 => 1,
    ]
];

function myFunc($arr) {
    return array_filter($arr, 'is_array');
}
$filtered = array_filter($list, 'myFunc');
var_dump($filtered);

/**
Output:

Array
(
    [07:15 AM - 07:20 AM] => Array
        (
            [0] => 1
            [1] => 1
            [2] => Array
                (
                    [schedule_id] => 10
                    [time] => 07:15 AM - 07:20 AM
                    [subject_name] => Subject Abc
                )

            [3] => 1
            [4] => 1
        )

)
*/

Edited:

By return array_filter($arr, 'is_array'); as a callback function its can extract the array on any index, not only index 2.

  • Related