将数据添加到数组
我正在尝试使用 while 循环将数据添加到数组中,但它似乎将数据作为字符串而不是数组添加。循环/数组是我仍在学习的东西,任何帮助都会很棒。
$c = 0;
$numberofcustom = 5;
$defaults = array(
'title' => __('Follow Us!', 'smw'),
'text' => ''
);
while ($c < $numberofcustom) {
$customnumber = $c + 1;
$defaults.=array(
'custom' . $customnumber . 'name' => __('', 'smw'),
'custom' . $customnumber . 'icon' => __('', 'smw'),
'custom' . $customnumber . 'url' => __('', 'smw')
);
$c++;
}
print_r($defaults);
问题似乎是从循环中添加数据,如果我只是在上面执行 print_r
,我就得到了“数组”。
任何帮助将不胜感激。
更新
我决定不需要多维数组,所以我使用了下面的建议并提出了
while( $c < $numberofcustom){
$customnumber = $c+1;
$defaults['custom'.$customnumber.'name'] = __('', 'smw');
$defaults['custom'.$customnumber.'icon'] = __('', 'smw');
$defaults['custom'.$customnumber.'url'] = __('', 'smw');
$c++;
}
I am trying a add data to an array using a while loop but it seems to be adding the data as a string not array. Loops/arrays are something I'm still learning any help would be great.
$c = 0;
$numberofcustom = 5;
$defaults = array(
'title' => __('Follow Us!', 'smw'),
'text' => ''
);
while ($c < $numberofcustom) {
$customnumber = $c + 1;
$defaults.=array(
'custom' . $customnumber . 'name' => __('', 'smw'),
'custom' . $customnumber . 'icon' => __('', 'smw'),
'custom' . $customnumber . 'url' => __('', 'smw')
);
$c++;
}
print_r($defaults);
The problem seems to be with adding the data from the loop if I do a print_r
just on that I just get "array" back.
Any help would be appreciated.
UPDATE
I decided I don't need a multi dimensional array so I used the suggestions below and came up with
while( $c < $numberofcustom){
$customnumber = $c+1;
$defaults['custom'.$customnumber.'name'] = __('', 'smw');
$defaults['custom'.$customnumber.'icon'] = __('', 'smw');
$defaults['custom'.$customnumber.'url'] = __('', 'smw');
$c++;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要这样做:
动态数组键几乎和具有动态名称的变量一样糟糕。使用另一个数组级别代替:
Don't do this:
dynamic array keys are almost as bad as variables with a dynamic name. Use another array level instead:
您需要使用
$arrayname[] = $var
,这是附加新项目的 PHP 语法。请参阅此页面。You need to use
$arrayname[] = $var
, that's the PHP syntax for appending new items. See this page.