在foreach循环PHP中添加数组中的键对值

时间:2017-10-17 05:57:41

标签: php arrays multidimensional-array foreach

我想在foreach的{​​{1}}循环中创建一个密钥对数组。在我的php我有城市名称和用户名。我想在阵列中添加同一城市的所有用户。

Ex foreach loop或任何其他数组格式。

[{city=>'pune',users=>("a","b","c","d")},{'city=>nk',users=>("e","b","c","f")}]

如何在数组中为同一foreach ($studsInfo as $value) { $studId = "".$value['_id']; $indDetail = $industryM->getAllIndustries($studId); $indusArray['industry'] = iterator_to_array($indDetail); $city = $value['city']; $name = $value['firstname']; } 添加所有name

提前谢谢,欢迎任何建议和编辑

1 个答案:

答案 0 :(得分:2)

您可以将城市作为城市的关键用户作为价值。

$arr = [];
foreach ($studsInfo as $value) {
    $studId = "".$value['_id'];
    $indDetail = $industryM->getAllIndustries($studId);
    $indusArray['industry'] = iterator_to_array($indDetail);
    //$city = $value['city'];
    //$name = $value['firstname'];
    $arr[$value['city'][] = $value['firstname'];
}
foreach($arr as $k => $v) {
    $result[] = array('city' => $k, 'users' => $v);
}