0

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
  • You would make an array of Start and Close times and match them with days? Commented Nov 8, 2017 at 22:13

1 Answer 1

1

You can achieve this by simply using a foreach loop, Like following:

$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);

Try it here: http://sandbox.onlinephpfunctions.com/

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant, quick solution. This can be used for a lot of issues like this. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.