如何使用PHP在循环中向数组添加元素 [英] how to add elements to an array in a loop using php

查看:1131
本文介绍了如何使用PHP在循环中向数组添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在动态尝试填充多维数组并遇到一些麻烦.

I am dynamically trying to populate a multidimensional array and having some trouble.

我有美国各州的清单.在我的循环中,像这样的关联数组$ states [nc],$ states [sc]等,我想将城市附加到每个州,因此$ states [nc] [cities]包含一个城市数组.我坚持逻辑.

I have a list of US states. Associative array like this $states[nc], $states[sc], etc. in my loop I want to append cities onto each state so $states[nc][cities] contains an array of cities. Im stuck with the logic.

foreach($states as $state) {
    $data[$state] = $state;

    foreach($cities as $city) {
      $data[$state]['cities'] .= $city;
     }
}

我知道串联是不正确的,但是我不确定如何向该数组添加元素.我不断收到关于array_push的错误.

I know that concatenation is not correct, but I am not sure how to add elements to this array. I keep getting errors with array_push.

添加这些元素的正确方法是什么?

What's the correct way to add these elements?

推荐答案

与键无关时添加到数组的方法相同:

The same way you add to an array when the key is not a concern:

$data[$state]['cities'][] = $city;

这篇关于如何使用PHP在循环中向数组添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆