Простой (но еще не решенный): это мой массив
[
[
"role" => "admin",
"name" => [
"Felipy",
"Ivan",
],
],
[
"role" => "user",
"name" => [
"Michel",
"Paul",
"Tay",
],
]
И я хотел бы увидеть этот результат:
[
"Felipy" => "admin",
"Ivan" => "admin",
"Michael" => "user",
"Paul" => "user",
"Tay" => "user",
]
Я уже пробовала array_flip
Попробуй это:
foreach ($yourArr as $role) {
foreach ($role['name'] as $user) {
$arr[$user] = $role['role'];
}
}
попробуй это 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'];
}
}
Попробуй это Живая демо
$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);
Менее понятное, но все еще работающее решение:
$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>';