【发布时间】:2017-11-23 21:01:57
【问题描述】:
所以我在变量 $Myarray 中有这个数组
{ [0]=> object(stdClass)#3216 (3)
{ ["id"]=> string(2) "11" ["name"]=> string(5) "david"}
{ ["id"]=> string(2) "12" ["name"]=> string(5) "linda"}
{ ["id"]=> string(2) "13" ["name"]=> string(5) "dony"}
所以我想使用 foreach 范围仅回显 id 12 到 13,问题是.. 我该怎么做?
因为在 php 中,我只能指定特定数组的范围,例如:
<?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $number) {
echo $number;
}
// The step parameter
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $number) {
echo $number;
}
// Usage of character sequences
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
foreach (range('a', 'i') as $letter) {
echo $letter;
}
// array('c', 'b', 'a');
foreach (range('c', 'a') as $letter) {
echo $letter;
}
?>
谢谢
【问题讨论】:
-
使用 php array_slice()
-
实现这一点的最佳方法是使用 Eloquent 而不是 Query Builder 来获取数据和集合方法,如
whereIn来迭代集合的指定部分。 -
这仅在我只有 3 个或更少数据时才有效,我有数百个需要范围的数据数组
标签: php arrays laravel web foreach