$array = [
[
"UF" => "Goias",
[
"Nome" => [
"Avenor",
"KENNEDY",
"JOSE"
],
"Fone" => [
"+55 (91) 1111-1111",
"+55 (33) 2222-2222",
"+55 (93) 3333-3333"
],
"Email" => [
"avenor@example.com",
"kennedy@example.com",
"sabino@example.com"
]
]
],
[
"UF" => "Amazonas",
[
"Nome" => [
"Kelsen",
"Joao",
"Kenia"
],
"Fone" => [
"+55 (91) 4444-4444",
"+55 (33) 5555-5555",
"+55 (93) 6666-6666"
],
"Email" => [
"kelsen@example.com",
"joao@example.com",
"kenia@example.com"
]
]
]
];
我想通过搜索此数组创建一个列表并填写列表。 例如:当用户选择“Goias”时,我必须通过数组搜索“Goias”并返回一个包含“Nome”,“Fone”和“Email”的列表,但我找不到循环此数组的方法并返回正确的值。
$selected = isset($_POST['selected']) ? $_POST['selected'] : 'nothing';
$key = array_search($selected,array_column($array, 'UF'));
foreach ($array[$key] as $data){
echo '<li><p>Nome: '.$data["Nome"].'</p><p>Fone: '.$data["Fone"].'</p><p>E-mail: '.$data["Email"].'</p></li>';
};
编辑:
我试着这样做:
echo
'<div class="representante-wrapper">
<h3>'.$selected.'</h3>';
foreach ($array[$key] as $data){
foreach($data as $value){
echo '<ul class="flex" id="dados" style="opacity: 1;">';
var_dump($value);
foreach($value["Nome"] as $nome){
echo '<li><p>Nome: '.$nome.'</p></li>';
}
foreach($value["Fone"] as $fone){
echo '<li><p>Fone: '.$fone.'</p></li>';
}
foreach($value["Email"] as $email){
echo '<li><p>E-mail: '.$email.'</p></li>';
}
echo '</ul>';
}
};
echo '</div>';
但结果不是我所期望的
Nome: Kelsen
Nome: Joao
Nome: Kenia
Fone: +55 (91) 4444-4444
Fone: +55 (33) 5555-5555
Fone: +55 (93) 6666-6666
E-mail: kelsen@example.com
E-mail: joao@example.com
E-mail: kenia@example.com
我希望如下所示,列表中的每个数组:
Nome: Kelsen
Fone: +55 (91) 4444-4444
E-mail: kelsen@example.com
Nome: Joao
Fone: +55 (33) 5555-5555
E-mail: joao@example.com
Nome: Kenia
Fone: +55 (93) 6666-6666
E-mail: kenia@example.com
答案 0 :(得分:0)
您可以尝试按键和值搜索,例如:
foreach ($array as $key => $value) {
// $key is "Goias"
// $value is an array with "nome", "fone" and "Email" keys
}
答案 1 :(得分:0)
$array = array("UF" => array("Goias"=> array("Nome" => array("Avenor","KENNEDY","JOSE"),
"Fone" => array("+55 (91) 1111-1111","+55 (33) 2222-2222","+55 (93) 3333-3333"),
"Email" => array("avenor@example.com","kennedy@example.com","sabino@example.com")
)
),
array(
"UF" => array("Amazonas"=>
array(
"Nome" => array(
"Kelsen",
"Joao",
"Kenia"
),
"Fone" => array(
"+55 (91) 4444-4444",
"+55 (33) 5555-5555",
"+55 (93) 6666-6666"
),
"Email" => array(
"kelsen@example.com",
"joao@example.com",
"kenia@example.com"
)
)
)
));
$selected = isset($_POST['selected']) ? $_POST['selected'] : 'nothing';
$i=0;
foreach($array as $key => $val){
if(isset($array[$i]['UF'][$selected])){
break;
}
$i++;
}
foreach ($array[$i]['UF'] as $data){
$li = '<li>';
foreach($data["Nome"] as $nome){
$li .= '<p>Nome:'.$nome.'</p>';
}
foreach($data["Fone"] as $nome){
$li .= '<p>Fone:'.$nome.'</p>';
}
foreach($data["Email"] as $nome){
$li .= '<p>E-mail:'.$nome.'</p>';
}
$li .= '</li>';
echo $li;
};