array_flip,其值为数组

时间:2017-06-05 08:11:21

标签: php arrays array-flip

简单的(但尚未解决):这是我的数组

[
 [
   "role" => "admin",
   "name" => [
     "Felipy",
     "Ivan",
   ],
 ],
 [
   "role" => "user",
   "name" => [
     "Michel",
     "Paul",
     "Tay",
 ],
]

我很想看到这个结果:

[
 "Felipy" => "admin",
 "Ivan" => "admin",
 "Michael" => "user",
 "Paul" => "user",
 "Tay" => "user",
]

我已经尝试过array_flip

4 个答案:

答案 0 :(得分:2)

试试这个:

foreach ($yourArr as $role) {
 foreach ($role['name'] as $user) {
    $arr[$user] = $role['role'];
 }
}

答案 1 :(得分:1)

试试这个DEMO

$original = [
     [
       "role" => "admin",
       "name" => [
         "Felipy",
         "Ivan",
       ],
     ],
     [
       "role" => "user",
       "name" => [
         "Michel",
         "Paul",
         "Tay",
        ],
      ]
    ];
    $arr = [];

    foreach ($original as $value)
    {
       foreach($value['name'] as $name)
       {
           $arr[$name] = $value['role'];
       }
    }

答案 2 :(得分:1)

试试这个Live demo

<li ng-repeat="item in allItems track by $index">

答案 3 :(得分:0)

不太清晰但仍然有效的解决方案:

$a = [
 [
   "role" => "admin",
   "name" => [
     "Felipy",
     "Ivan",
   ],
 ],
 [
   "role" => "user",
   "name" => [
     "Michel",
     "Paul",
     "Tay",
    ],
 ],
];

$r = [];
foreach ($a as $item) {
    $r = array_merge($r, array_fill_keys($item['name'], $item['role']));
}
echo'<pre>',print_r($r),'</pre>';