将多维数组拆分为具有相同键值的子数组

时间:2018-07-25 06:32:40

标签: php arrays

我有一个具有相同键值uid的多维数组。 通过限制foreach循环将其转换为子数组。您可以看到 两个uid的值为100,两个uid的值为5465

$userdb=Array
(
    0 => Array
    (
        "uid"=> '100',
        "name" => 'Sandra Shush',
        "url"=> 'urlof100'
    ),

1 => Array
    (
        "uid"=> '5465',
        "name" => 'Sandra Shush',
        "url"=> 'urlof100'
    ),

2 => Array
    (
            "uid"=> '100',
        "name" => 'Sandra Shush',
        "url"=> 'urlof100'
    ),
3 => Array
    (
        "uid"=> '5465',
        "name" => 'Sandra Shush',
        "url"=> 'urlof100'
    ),

);

我想要这样的数组。

$userdb=Array
(

  0 => Array(
      0 => Array
      (
          "uid"=> '100',
          "name" => 'Sandra Shush',
          "url"=> 'urlof100'
      ),
      2 => Array
      (
          "uid"=> '100',
          "name" => 'Sandra Shush',
          "url"=> 'urlof100'
      )
    ),
  1=> Array(
    1 => Array
    (
        "uid"=> '5465',
        "name" => 'Sandra Shush',
        "url"=> 'urlof100'
    ),
    3 => Array
    (
        "uid"=> '5465',
        "name" => 'Sandra Shush',
        "url"=> 'urlof100'
    )
  )
);

我可以不使用foreach循环而得到结果吗?

2 个答案:

答案 0 :(得分:2)

app.post('myurl.com', function(req,res) {
  const user = req.body.data
  const pass = req.body.otherData
  const token = await db.call(req,res,user,pass)
  \\ res.json = token ?
})

输出:

Caused by: java.lang.IllegalArgumentException: The concrete class implementing IObjectWrapper must have exactly *one* declared private field for the wrapped object.  Preferably, this is an instance of the ObjectWrapper<T> class.
        at aolk.a(SourceFile:13)
        at com.google.android.youtube.api.jar.client.RemoteEmbeddedPlayer.<init>(SourceFile:42)

答案 1 :(得分:2)

没有循环是不可能的,但是您可以将循环限制为唯一的uid。

// Get all uids to an flat array
$uid = array_column($userdb, "uid");

// Loop the unique uids and find all matching uids and place them in array
foreach(array_unique($uid) as $id){
    $new[] = array_intersect_key($userdb, array_intersect($uid, [$id]));
}
var_dump($new);

这将返回您预期的结果。

https://3v4l.org/nWFVP