0

I have he next array looks like:

array:50 [▼
  0 => array:39 [▶]
  1 => array:39 [▶]
  2 => array:39 [▶]
]

So I want to get arrays with a value in common, for example:

array:39 [▼
    "id" => 121
    "user" => 368
]
array:39 [▼
    "id" => 121
    "user" => 3687
]
array:39 [▼
    "id" => 500
    "user" => 452
]

I want to get the two arrays with the attribute id 121, I was trying to looping the array with foreach looks like:

foreach ($info as $val){
       foreach($info as $f ){
           if($f["id"]==$val["id"]){
                //get the multiple arrays
           }
       }
}

So, I can't get all the arrays, some idea to how can do that?

5
  • By you sample it's hard to gues which is which but I's used something like (pseudo code) foreach($info as $key => $f ) { if ($f['id']==121) {var_dump($info[$key]);}} Commented Jun 1, 2021 at 15:43
  • You try to iterate the same array twice, first foreach ($info as $val) then foreach($info as $f ). The inner loop should be over $val, not $info again. Commented Jun 1, 2021 at 15:44
  • Though, you need nothing more than array_filter here, with a custom callback that compares each element's id key to your desired value. Commented Jun 1, 2021 at 15:46
  • @El_Vanja Your comment helped me to give me an idea, Thanks Commented Jun 1, 2021 at 16:39
  • Since this is tagged Laravel then there's also the option of $filtered = collect($array)->where('id', '=', 121) Commented Jun 2, 2021 at 6:18

1 Answer 1

3

I'd use a Collection.

  1. collect your array of arrays:
$collection = collect([
    [
        "id" => 121
        "user" => 368
    ],
    [
        "id" => 121
        "user" => 3687
    ],
    [
        "id" => 500
        "user" => 452
    ]
]);
  1. Use the where method to filter based on a specific key's value:
$filtered = $collection->where('id', 121);

$filtered->all();

/*
    [
        ['id' => '121', 'user' => 368],
        ['id' => '121', 'user' => 3687],
    ]
*/

Other where-like methods are available. Be sure to read through all of the documentation on Collections, it's full of great examples!

If you're now convinced that you should use Collections for everything, check out Adam Wathan's awesome book (and other resources): Refactoring to Collections (not free)

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.