我想在while循环中填充一个数组。
我想像这样显示这个数组:
category 1 => Company A => 'name', 'city', 'CEO',
Company B => 'name', 'city', 'CEO'
category 2 = Company A => 'name', 'city', 'CEO',
Company B => 'name', 'city', 'CEO'
ect ........
这是我在while循环中的当前代码
$array_cat[] = array(
array(
'category' => $cat,
array(
'company' => array(
'name' => $name,
'city' => $city,
'CEO' => $ceo
)
)
)
);
我的代码我显示它
foreach ($array_cat as $item) {
foreach ($array_cat['category'] as $company_display) {
echo $company_display['company']['name'][];
}
}
感谢您的帮助;)
答案 0 :(得分:2)
试试这个:
$array1 = array('category1' =>
array('Company A' =>
array('name', 'city', 'CEO')),
'category2' =>
array('Company B' =>
array('name', 'city', 'CEO')));
foreach ($array1 as $key => $value)
{
foreach ($value as $key1 => $value1)
{
echo "<pre>";
print_r($value1);
echo "</pre>";
}
}
问题在于你的内在的foreach循环
答案 1 :(得分:0)
内部foreach循环和回声线存在问题。
将 $ array_cat 替换为 $ item ,并在echo行中出现错误: 无法使用 [] 进行阅读
通过以下方式,您可以实现目标。
SPACESHIP
答案 2 :(得分:0)
如何在PHP中创建这个多维数组
如果我为此设计一个数组,我会做这样的事情:
$array = array(
//Category 1, nameless i assume?
array(
//Companies
"Company A" => array(
//Company properties
"name" => "My A company",
"city" => "Some city that starts with an A",
"CEO" => "Some CEO that starts with an A"
),
"Company B" => array(
//Company properties
"name" => "My B company",
"city" => "Some city that starts with an B",
"CEO" => "Some CEO that starts with an B"
),
),
//Category two, nameless i assume
array(
//Companies
"Company C" => array(
//Company properties
"name" => "My C company",
"city" => "Some city that starts with an C",
"CEO" => "Some CEO that starts with an C"
),
"Company D" => array(
//Company properties
"name" => "My D company",
"city" => "Some city that starts with an D",
"CEO" => "Some CEO that starts with an D"
),
),
);
然后,如果我想从中获取一些数据,我可以这样做:
$companyAcity = $array[0]['Company A']['city'];
echo $companyAcity;
如果我想循环数组,我可以这样:
for($categoryID = 0; categoryID < count($array); $i++) {
//Prints data for each category it loops through.
echo $array[$categoryID];
//Loops through the companies contained in the current category where it's looping through
foreach($array[$categoryID] as $companyName => $companyData) {
echo $companyName;
echo $companyData['name'];
}
}
我想在while循环中填充一个数组。
如果要在循环中向数组添加数据,可以执行以下操作:
for($categoryID = 0; categoryID < count($array); $i++) {
$array[$categoryID][] = $categoryID +1;
}