是否可以在数组中执行if / else或switch语句?
例如我有这个数组
'images' => array(
array(
'link' => 'http://graphics.edc-internet.nl/500/' . (string)$product->artikelnummer .'.jpg'
),
),
现在我想检查是否有超过1个图像,如果是,则添加一个数组。 我的想法是这样,但它不起作用。
<?php
$images = (string)$product->aantalfotos;
'images' => array(
switch ($images) {
case 1:
array(
'link' => 'http://graphics.edc-internet.nl/500/' . (string)$product->artikelnummer .'.jpg'
),
break;
case 2:
array(
'link' => 'http://graphics.edc-internet.nl/500/' . (string)$product->artikelnummer .'.jpg'
),
array(
'link' => 'http://graphics.edc-internet.nl/500/' . (string)$product->artikelnummer .'_2.jpg'
),
break;
case 3:
array(
'link' => 'http://graphics.edc-internet.nl/500/' . (string)$product->artikelnummer .'.jpg'
),
array(
'link' => 'http://graphics.edc-internet.nl/500/' . (string)$product->artikelnummer .'_2.jpg'
),
array(
'link' => 'http://graphics.edc-internet.nl/500/' . (string)$product->artikelnummer .'_3.jpg'
),
break;
}
),
答案 0 :(得分:1)
试试这段代码:
<?php
$images = (string)$product->aantalfotos;
for ($working = array(), $i = 1, $suffix = ''; $i <= $images; $i++)
{
$working[] = array('link' => 'http://graphics.edc-internet.nl/500/'.(string)$product->artikelnummer.$suffix.'.jpg');
$suffix = '_'.($i + 1);
}
// Use $working in 'images' => $working
?>
答案 1 :(得分:0)
你可以这样做:
aantalfotos;
switch($images) {
case 1:
$x = array('link' => 'http://graphics.edc-internet.nl/500/' . (string)$product->artikelnummer . '.jpg');
break;
case 2:
$x = array('link' => 'http://graphics.edc-internet.nl/500/' . (string)$product->artikelnummer . '.jpg',
array('link' => 'http://graphics.edc-internet.nl/500/' . (string)$product->artikelnummer . '_2.jpg'));
break;
case 3:
$x = array('link' => 'http://graphics.edc-internet.nl/500/' . (string)$product->artikelnummer . '.jpg',
array('link' => 'http://graphics.edc-internet.nl/500/' . (string)$product->artikelnummer . '_2.jpg'),
array('link' => 'http://graphics.edc-internet.nl/500/' . (string)$product->artikelnummer . '_3.jpg'));
break;
}
if(!empty($x)) {
$images[] = ($x);
}
print_r($images);