I have an Array as bellow
array(
(int) 0 => array(
'Homeslider' => array(
'id' => '1',
'title' => null,
'display_photo' => '1402379775bdaebd329b69.jpg',
'order_no' => null,
'created' => '2014-06-10 05:56:15',
'modified' => '2014-06-10 05:56:15'
)
),
(int) 1 => array(
'Homeslider' => array(
'id' => '2',
'title' => null,
'display_photo' => '1402379784a426fe476711.jpg',
'order_no' => null,
'created' => '2014-06-10 05:56:24',
'modified' => '2014-06-10 05:56:24'
)
),
(int) 2 => array(
'Homeslider' => array(
'id' => '3',
'title' => null,
'display_photo' => '1402379793cb81f1a5bbf9.jpg',
'order_no' => null,
'created' => '2014-06-10 05:56:33',
'modified' => '2014-06-10 05:56:33'
)
)
)
What i am trying to achieve
["img/default/slide/bg1.jpg","img/default/slide/bg2.jpg","img/default/slide/bg3.jpg"]
what i tried?
var slider_container = [];
<?php foreach($sliders as $slide): ?>
slider_container[] = "img/sliders/<?php echo $slide['Homeslider']['display_photo'] ?>";
<?php endforeach; ?>
console.log(slider_container);
Error
JavaScript doesn't support PHP's array[] = ...
syntax, but you don't need it here, either.
Two options:
json_encode
: var slider_container =
<?php
$images = [];
foreach($sliders as $slide) {
$images[] = $slide['Homeslider']['display_photo'];
}
echo json_encode($images);
?>;
(My PHP-fu is weak, apologies for errors in the PHP of that.)
var slider_container = [
<?php foreach($sliders as $slide): ?>
"img/sliders/<?php echo $slide['Homeslider']['display_photo'] ?>",
<?php endforeach; ?>
""
];
--slider_container.length;
console.log(slider_container);
Note that game I had to play there with the commas, putting in an extra entry at the end just to remove it afterward. Most modern browsers would just ignore the trailing comma, but there are still a couple kicking around that would leave an undefined
entry at the end, so for max compat you might consider this. (More on the trailing comma in this post on my blog .)
I don't really like to mix js and php, it gets ugly and editors don't like (indententation and so on).
I'd do something like:
<?php
foreach($arr as $val) {
$filteredArr[] = "img/sliders/".$val['Homeslider']['display_photo'];
}
?>
<span id="arrayEl" style="display:none"><?=json_encode($filteredArr);?></span>
<script>
var slider_container = JSON.parse(document.getElementById("arrayEl").innerText);
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.