[英]PHP loop to generate array
我不太熟悉,但是确定应该有一些方法可以缩短我的代码。 我有如下的多维数组。
return array(
'save' => 'here is the save message',
'options' => array(
// section for item 1
array(
'name' => 'Item 1',
'type' => 'text',
'id' => 'item_1_type_1',
),
array(
'name' => 'Item 2',
'type' => 'text',
'id' => 'item_1_type_2',
),
array(
'name' => 'Item 3',
'type' => 'text',
'id' => 'item_1_type_3',
),
// section for item 2
array(
'name' => 'Item 1',
'type' => 'text',
'id' => 'item_2_type_1',
),
array(
'name' => 'Item 2',
'type' => 'text',
'id' => 'item_2_type_2',
),
array(
'name' => 'Item 3',
'type' => 'text',
'id' => 'item_2_type_3',
),
// here I also may add more fields aprart from loop
// but that would be an array with the same format
'submit' => array(
'name' => 'Save Options',
'id' => 'save_theme_options'
),
),
);
现在我总共有10个项目(请参考ID),每个项目有10个字段(在参考代码中只有3个)。 因此,如果我为每个字段编写代码,它将在100个数组附近变得庞大,因此我正在寻找某种方式可以为每个项目重复循环。
我希望我能正确解释。
您需要在数据中找到模式并创建代码,生成这些模式,而不是手工编写所有内容:
<?php
$array = array(
'save' => 'here is the save message',
'options' => array(),
);
$n = 2;
$m = 3;
for ($i = 1; $i <= $n; ++$i)
{
for ($j = 1; $j <= $m; ++$j)
{
$element = array(
'name' => "Item $i",
'type' => 'text',
'id' => "item_" . $i . "_type_$j",
);
array_push($array['options'], $element);
}
}
$array['options']['submit'] = array(
'name' => 'Save Options',
'id' => 'save_theme_options'
);
var_dump($array);
印刷品:
array(2) {
["save"]=>
string(24) "here is the save message"
["options"]=>
array(7) {
[0]=>
array(3) {
["name"]=>
string(6) "Item 1"
["type"]=>
string(4) "text"
["id"]=>
string(13) "item_1_type_1"
}
[1]=>
array(3) {
["name"]=>
string(6) "Item 1"
["type"]=>
string(4) "text"
["id"]=>
string(13) "item_1_type_2"
}
[2]=>
array(3) {
["name"]=>
string(6) "Item 1"
["type"]=>
string(4) "text"
["id"]=>
string(13) "item_1_type_3"
}
[3]=>
array(3) {
["name"]=>
string(6) "Item 2"
["type"]=>
string(4) "text"
["id"]=>
string(13) "item_2_type_1"
}
[4]=>
array(3) {
["name"]=>
string(6) "Item 2"
["type"]=>
string(4) "text"
["id"]=>
string(13) "item_2_type_2"
}
[5]=>
array(3) {
["name"]=>
string(6) "Item 2"
["type"]=>
string(4) "text"
["id"]=>
string(13) "item_2_type_3"
}
["submit"]=>
array(2) {
["name"]=>
string(12) "Save Options"
["id"]=>
string(18) "save_theme_options"
}
}
}
$sections = "Section1,Section2";
$itemCount = 3; // how many items you need
$generated = array(); // generated array
foreach(explode(",",$sections) as $k/*for index number*/=>$v/*section name*/)
{
for(int i = 0; i < $itemCount; $i++)
{
$generated[] = array("name" => "Item ".($i+1/*starts from 0*/), "type"=> "item", "id" => "$v_$k_type_$i");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.