-1

Simple one (but not solved yet): this is my array

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

And I would love to see this result:

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

I've already tried array_flip

4

4 回答 4

2

尝试这个:

foreach ($yourArr as $role) {
 foreach ($role['name'] as $user) {
    $arr[$user] = $role['role'];
 }
}
于 2017-06-05T08:17:45.533 回答
1

试试这个现场演示

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

$result = array_reduce($array, function($carry, $key) {
    foreach ($key['name'] as $name)
        $carry[$name] = $key['role'];
    return $carry;
}, []);

var_dump($result);
于 2017-06-05T08:22:08.483 回答
1

试试这个演示

$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'];
       }
    }
于 2017-06-05T08:14:17.400 回答
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>';
于 2017-06-05T08:18:16.717 回答