如何在php中为数组分配一系列值?

时间:2017-08-14 09:55:15

标签: 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->tocountry->name; 
        $route_selection[] = [$route->hash_id => 'From: '.$from_state.' ('.$from_country.') To: '.$to_state.' ('.$to_country.')'];
    }

果然,它会产生这样的结果: enter image description here

但我希望结果是这样的: enter image description here

我怎么能用PHP做到这一点?

4 个答案:

答案 0 :(得分:4)

将阵列分配线更改为:

$route_selection[$route->hash_id] = 'From: '.$from_state.' ('.$from_country.') To: '.$to_state.' ('.$to_country.')';

只要每个hash_id都是唯一的,这将为每条路线创建一个新的数组元素。

答案 1 :(得分:1)

$array => array(pWjY=>'Value',
                YA8N=>'Value',);

您可以添加第三个值:

$array['somekey'] = 'Value';

答案 2 :(得分:1)

更改此行

$route_selection[] = [$route->hash_id => 'From: '.$from_state.' ('.$from_country.') To: '.$to_state.' ('.$to_country.')'];

$route_selection[$route->hash_id] =  'From: '.$from_state.' ('.$from_country.') To: '.$to_state.' ('.$to_country.')';

答案 3 :(得分:1)

这样做:

CAAnimation