Seperate matching values in array to new array

时间:2017-11-08 21:58:55

标签: php arrays

So I have an array of days and times that I need to separate into matching days coordinating with times. I have tried intersect associative and other array functions but cant seem to find one that does this. Has anyone had to of done this before?

Array
(
[Monday] => Array
    (
        [0] => 9:00 am
        [1] => 5:00 pm
    )

[Tuesday] => Array
    (
        [0] => 9:00 am
        [1] => 5:00 pm
    )

[Wednesday] => Array
    (
        [0] => 9:00 am
        [1] => 3:00 pm
    )

[Thursday] => Array
    (
        [0] => 9:00 am
        [1] => 2:00 pm
    )

[Friday] => Array
    (
        [0] => 9:00 am
        [1] => 2:00 pm
    )

[Saturday] => Array
    (
        [0] => 9:00 am
        [1] => 5:00 pm
    )

)

I need to grab all the days that have the same open and close times and put them in their own arrays like:

Array
(
[Monday] => Array
    (
        [0] => 9:00 am
        [1] => 5:00 pm
    )

[Tuesday] => Array
    (
        [0] => 9:00 am
        [1] => 5:00 pm
    )


[Saturday] => Array
    (
        [0] => 9:00 am
        [1] => 5:00 pm
    )

)


Array
(
[Wednesday] => Array
    (
        [0] => 9:00 am
        [1] => 3:00 pm
    )
)


Array{
[Thursday] => Array
    (
        [0] => 9:00 am
        [1] => 2:00 pm
    )

[Friday] => Array
    (
        [0] => 9:00 am
        [1] => 2:00 pm
    )
)

1 个答案:

答案 0 :(得分:1)

您只需使用foreach循环即可实现此目的,如下所示:

$result = [];

foreach ($a as $k => $value) {

    // create a unique key from times values
    $key = join($value);

    // if the key isn't already existing, we create a new array with this key
    if( !isset( $result[$key] ) ) {

        $result[$key] = [];

    }

    $result[$key][$k] = $value;

}

$result = array_values($result);

在此处试试:http://sandbox.onlinephpfunctions.com/