如何在php中为数组分配一系列值?
我使用foreach循环为数组赋值如何在php中为数组分配一系列值?,php,arrays,Php,Arrays,我使用foreach循环为数组赋值 $route_selection; foreach ($routes as $route) { $from_state = $route->fromState->name; $to_state = $route->toState->name; $from_country = $route->fromCountry->name; $to_country =
$route_selection;
foreach ($routes as $route) {
$from_state = $route->fromState->name;
$to_state = $route->toState->name;
$from_country = $route->fromCountry->name;
$to_country = $route->tocountry->name;
$route_selection[] = [$route->hash_id => 'From: '.$from_state.' ('.$from_country.') To: '.$to_state.' ('.$to_country.')'];
}
果不其然,它将产生如下结果:
但我希望结果是这样的:
如何在PHP中实现这一点?将数组赋值行更改为:
$route_selection[$route->hash_id] = 'From: '.$from_state.' ('.$from_country.') To: '.$to_state.' ('.$to_country.')';
只要每个hash_id是唯一的,这将为每个路由创建一个新的数组元素
$array => array(pWjY=>'Value',
YA8N=>'Value',);
您可以通过以下方式添加第三个值:
$array['somekey'] = 'Value';
换行
$route_selection[] = [$route->hash_id => 'From: '.$from_state.' ('.$from_country.') To: '.$to_state.' ('.$to_country.')'];
到
这样做:
$route_selection;
foreach ($routes as $route) {
$from_state = $route->fromState->name;
$to_state = $route->toState->name;
$from_country = $route->fromCountry->name;
$to_country = $route->tocountry->name;
$route_selection[$route->hash_id] = 'From: '.$from_state.' ('.$from_country.') To: '.$to_state.' ('.$to_country.')' ;
}
这不会产生他想要的输出,他会得到嵌套数组。是的。它起作用了。感谢您的快速解决方案。我是php数组的新手,非常感谢。谢谢。@JayMarz不要忘记接受最适合您的问题的答案,这样其他用户就可以节省时间,好的答案也会得到奖励。@ksjohn是的。还有6分钟检查答案。@JayMarz完美!抱歉,我没注意到问题这么年轻。这些问题回答得很快。@JayMarz没问题,很高兴我能帮上忙!
$route_selection;
foreach ($routes as $route) {
$from_state = $route->fromState->name;
$to_state = $route->toState->name;
$from_country = $route->fromCountry->name;
$to_country = $route->tocountry->name;
$route_selection[$route->hash_id] = 'From: '.$from_state.' ('.$from_country.') To: '.$to_state.' ('.$to_country.')' ;
}