2017-10-17 124 views
2

我想在循環中創建一個密鑰對數組php。在我的foreach loop我有城市名稱和用戶名。我想爲數組中的同一個城市添加所有用戶。在foreach循環中添加數組中的密鑰對值PHP

Ex [{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在陣列相同city

Thankx提前,任何建議和編輯,歡迎

回答

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); 
} 
+1

Thnkx很多,這真的幫助我。 – Vivek

相關問題