我在php上有这样的数组:
echo "<pre>";
print_r($header_item);
结果是:
Array
(
[0] => stdClass Object
(
[NO_INSPECTION] => 47
[ID_CONDITION] => 1
[NAMA_CONDITION] => DIRTY
)
[1] => stdClass Object
(
[NO_INSPECTION] => 47
[ID_CONDITION] => 2
[NAMA_CONDITION] => DAMAGE
)
[2] => stdClass Object
(
[NO_INSPECTION] =>
[ID_CONDITION] =>
[NAMA_CONDITION] => CLEAN
)
[3] => stdClass Object
(
[NO_INSPECTION] =>
[ID_CONDITION] =>
[NAMA_CONDITION] => OFF HIRE
)
)
我有这样的情况,这个数组将分为两个新的数组对象,基于偶数和赔率索引。所以我这样写:
<?php
$odd = array();
$even = array();
$breakrow = 0;
foreach ($header_item as $v) {
if ($breakrow % 2 == 0) {
array_push($even, $v->NO_INSPECTION);
array_push($even, $v->ID_CONDITION);
array_push($even, $v->NAMA_CONDITION);
} else {
array_push($odd, $v->NO_INSPECTION);
array_push($odd, $v->ID_CONDITION);
array_push($odd, $v->NAMA_CONDITION);
}
$breakrow++;
}
?>
但我得到了这样的新阵列:
echo "<pre>";
print_r($even);
echo "<br>";
echo "<pre>";
print_r($odd);
Array
(
[0] => 47
[1] => 1
[2] => DIRTY
[3] =>
[4] =>
[5] => CLEAN
)
Array
(
[0] => 47
[1] => 2
[2] => DAMAGE
[3] =>
[4] =>
[5] => OFF HIRE
)
我怎么能这样做:
Array
(
[0] => stdClass Object
(
[NO_INSPECTION] => 47
[ID_CONDITION] => 1
[NAMA_CONDITION] => DIRTY
)
[1] => stdClass Object
(
[NO_INSPECTION] =>
[ID_CONDITION] =>
[NAMA_CONDITION] => CLEAN
)
AND:
Array
(
[0] => stdClass Object
(
[NO_INSPECTION] => 47
[ID_CONDITION] => 2
[NAMA_CONDITION] => DAMAGE
)
[1] => stdClass Object
(
[NO_INSPECTION] =>
[ID_CONDITION] =>
[NAMA_CONDITION] => OFF HIRE
)
答案 0 :(得分:4)
你可以使用array_walk
和关键的偶数与奇数的简单测试来实现这一点。
$header_item = [
0 => 'zero',
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four',
5 => 'five',
6 => 'six',
7 => 'seven'
];
$odd = array();$even = array();
array_walk($header_item,function($value,$key) use(&$odd,&$even){
if ($key%2==0) {
$even[]=$value;
}
else{
$odd[]=$value;
}
});
print_r($even);
print_r($odd);
将输出
Array
(
[0] => zero
[1] => two
[2] => four
[3] => six
)
Array
(
[0] => one
[1] => three
[2] => five
[3] => seven
)
答案 1 :(得分:2)
试试这个: -
$odd = array();
$even = array();
$breakrow = 0;
foreach ($header_item as $v) {
if ($breakrow % 2 == 0) {
$even[] = $v;
} else {
$odd[] = $v;
}
$breakrow++;
}
echo '<pre>'; print_r($even).'<br>';
echo '<pre>'; print_r($odd).'<br>';
输出: -
Array
(
[0] => Array
(
[NO_INSPECTION] => 47
[ID_CONDITION] => 1
[NAMA_CONDITION] => DIRTY
)
[1] => Array
(
[NO_INSPECTION] =>
[ID_CONDITION] =>
[NAMA_CONDITION] => CLEAN
)
)
Array
(
[0] => Array
(
[NO_INSPECTION] => 47
[ID_CONDITION] => 2
[NAMA_CONDITION] => DAMAGE
)
[1] => Array
(
[NO_INSPECTION] =>
[ID_CONDITION] =>
[NAMA_CONDITION] => OFF HIRE
)
)