1

I want to make an key pair array in foreach loop in php. In my foreach loop i have city name and user name. I want to add all users for same city in array.

Ex [{city=>'pune',users=>("a","b","c","d")},{'city=>nk',users=>("e","b","c","f")}] or any other array format.

foreach ($studsInfo as $value) {
    $studId = "".$value['_id'];
    $indDetail = $industryM->getAllIndustries($studId);
    $indusArray['industry'] = iterator_to_array($indDetail);
    $city = $value['city'];
    $name = $value['firstname'];
}

How could I add all name in array for same city.

Thankx in advance, Any suggestion and editing are welcome

1 Answer 1

4

You can use the city as the key users from the city as value.

$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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thnkx a lot, this really helps me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.