当我为print_r输出执行foreach循环时,我可以成功输出$ key但输出$ cats时输出为'array'。我需要将哪个索引传递给varibale $ cats [??]。我是否需要View中的另一个foreach循环,还是需要重新组织控制器中的数组? (我试过两次没有成功)。你可以告诉我,我不是编程的主人。感谢您的耐心和任何指导!
查看:
<?php foreach($categories_sorted as $key => $cats) : ?>
<div class="box_container">
<div class="box_head"><?= $key; ?></div>
<div class="box_body"><?= $cats; ?></div>
</div>
<?php endforeach; ?>
的print_r:
Array
(
[Things to Do] => Array
(
[0] => Activities and Attractions
[1] => Castles
[2] => Golf
[3] => Islands and Beaches
[4] => Kids and Family
[5] => Landmarks and Architecture
[6] => Museums and Galleries
[7] => Nightlife
[8] => Parks and Gardens
[9] => Shopping
[10] => Sports and Outdoor
[11] => Tours Tracks and Cruises
[12] => Tracks and Trails
[13] => Wellness
)
[Transportation] => Array
(
[0] => Airport Transfers
[1] => Car Leasing
[2] => Flights
[3] => Public Transport
[4] => Taxis
[5] => Transport Lift Ride
[6] => Vehicle Rental
[7] => Vehicle Sales
)
)
控制器:
function categories(){
$this->load->model('array_model');
$category_row = $this->array_model->get_categories_all();
$arr_maincats = array();
foreach($category_row as $row){
if(!isset($arr_maincats[$row['category']]))
$maincats = $row['maincategory'];
$arr_maincats[$maincats][] = $row['category'];
}
$data['categories_sorted'] = $arr_maincats;
$this->load->view('array_view', $data);
答案 0 :(得分:2)
您可以按照建议在现有循环中使用foreach来显示所有$cat
选项:
<?php foreach($categories_sorted as $key => $cats) : ?>
<div class="box_container">
<div class="box_head"><?= $key; ?></div>
<div class="box_body">
<?php foreach($cats as $item) { echo $item; } ?>
</div>
</div>
<?php endforeach; ?>
或者,您可以使用join或implode将$cats
数组“折叠”为单个字符串,并输出:
<?php foreach($categories_sorted as $key => $cats) : ?>
<div class="box_container">
<div class="box_head"><?= $key; ?></div>
<div class="box_body">
<?php echo implode(', ', $cats); ?>
</div>
</div>
<?php endforeach; ?>
(这里我选择在每个$ cats项目之间添加,
。
答案 1 :(得分:2)
从print_r可以看出,你有包含数组的Array,所以你也需要遍历包含的数组。为了更多的理解,我将在下面添加一个这样的数组声明:
<?php
$categories_sorted = array(
'Things to Do' => array(
0 => 'Activities and Attractions',
1 => 'Castles',
2 => 'Golf',
3 => 'Islands and Beaches'
),
'Transportation' => array(
0 => 'Airport Transfers',
1 => 'Car Leasing',
2 => 'Flights',
3 => 'Public Transport'
)
);
?>
<?php foreach($categories_sorted as $key => $cats) : ?>
<div class="box_container">
<div class="box_head"><?= $key; ?></div>
<?php foreach($cats as $k => $cat): ?>
<div class="box_body"><?= $cat; ?></div>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
取决于你的需求,如果你需要创建<div class="box_body">
,你应该考虑在哪里放置第二个foreach。
答案 2 :(得分:1)
这是因为<?=
的功能与echo
相同,所以当您尝试<?= $cat
时,它会array
。如果你使用print_r($cat)
答案 3 :(得分:1)
在“另请参阅”部分中查看var_dump
及其相关功能: