Php 从多维阵列中获取前3项
我需要在数组上循环并回显前3个元素,但是我的问题是前3个元素并不总是在第一个父元素中。在下面的示例中,我需要获取内部元素“Items”的前3个Php 从多维阵列中获取前3项,php,Php,我需要在数组上循环并回显前3个元素,但是我的问题是前3个元素并不总是在第一个父元素中。在下面的示例中,我需要获取内部元素“Items”的前3个 array( 0 => array( 'Items' => array( 0 => "dave", 1 => "steve" ) ), 1 => array( 'Items' => array(
array(
0 => array(
'Items' => array(
0 => "dave",
1 => "steve"
)
),
1 => array(
'Items' => array(
0 => "megan"
)
)
)
在那个例子中,预期的结果将产生回声
戴夫
史蒂夫
梅根
非常感谢!:) 这将打印出正确的输出:
$array = array(
0 => array(
'Items' => array(
0 => "dave",
1 => "steve"
)
),
1 => array(
'Items' => array(
0 => "megan"
)
)
);
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
for($i = 0; $i < 3; $i++) {
$it->next();
$value = $it->current();
echo $value, " ";
}
$array=array(
0=>数组(
'Items'=>数组(
0=>“dave”,
1=>“史蒂夫”
)
),
1=>数组(
'Items'=>数组(
0=>“megan”
)
)
);
$it=new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
对于($i=0;$i<3;$i++){
$it->next();
$value=$it->current();
回声$value,“;
}
对于小型数组,可以使用数组\u walk\u recursive
:
$output = array();
array_walk_recursive($array, function ($value, $key, $elements) {
if (count($elements) < 3) {
$elements[] = $value;
}
}, $output);
这是我的代码:
<?php
$arr = array( 0 => array('Items' => array(0 => "dave",1 => "steve")),1 => array('Items' => array(0 => "megan")));
$out = '';
$c = 0;
foreach($arr as $all_items) {
foreach($all_items['Items'] as $ne_items) {
$out .= $ne_items.' ';
$c++;
if($c == 3) {
break;
}
}
if($c == 3) {
break;
}
}
echo $out;
嵌套的foreach循环和一个计数器来获取前三个循环有什么问题吗?这就是我目前得到的,我希望使用一个好的迭代器,但我想这可以做到-只是一个客户端的小脚本。干杯
<?php
$arr = array( 0 => array('Items' => array(0 => "dave",1 => "steve")),1 => array('Items' => array(0 => "megan")));
$out = '';
$c = 0;
foreach($arr as $all_items) {
foreach($all_items['Items'] as $ne_items) {
$out .= $ne_items.' ';
$c++;
if($c == 3) {
break;
}
}
if($c == 3) {
break;
}
}
echo $out;