0

I have the following array, i just need a way to select only arrays where mnth value is the same. eg all arrays where mnth value => 7.

  Array
(
    [0] => Array
        (
            [desc] => rates
            [mnth] => 7
            [cost] => 8978
        )

    [1] => Array
        (
            [desc] => insurance
            [mnth] => 8
            [cost] => 7680
        )


    [2] => Array
        (
            [desc] => water
            [mnth] => 7
            [cost] => 7800
        )

)
6
  • 3
    That sounds like a great challenge, Can you please show us what code you've tried so far? Commented Mar 2, 2018 at 0:22
  • 1
    Show us your exact expected output given your sample input and your best coding attempt so far. I'd bet my lunch that you're asking a duplicate question here. Have you searched StackOverflow for existing solutions? Commented Mar 2, 2018 at 0:22
  • Use a loop and an if statement Commented Mar 2, 2018 at 0:23
  • echo $array[0]['mnth']; Commented Mar 2, 2018 at 0:24
  • @westnblue do not add question details as comments. Edit your question and make it complete. Commented Mar 2, 2018 at 0:25

1 Answer 1

2

If you need to split a large array into separate arrays based on the mnth field you can do that in one pass. Create an empty array of arrays, loop through the arrays you have and store them in the new array of arrays using the mnth value as the key. Then for each key in the new array you have an array of arrays with the same mnth value.

If you need to just filter based on a value on mnth You can use array_filter but this isn't the way to do it if you need to split the array.

$myFilteredArray = array_filter( $myArray, function( $arr ) {
   return $arr['mnth'] == 7; 
});
Sign up to request clarification or add additional context in comments.

Comments

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.