简体   繁体   中英

How to get multiple arrays from an array in php?

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM