我正在使用PHP而且我有来自查询的数组
Array
(
[0] => stdClass Object
(
[question_id] => 13
[is_break] => 0
)
[1] => stdClass Object
(
[question_id] => 14
[is_break] => 1
)
[2] => stdClass Object
(
[question_id] => 15
[is_break] => 0
)
[3] => stdClass Object
(
[question_id] => 16
[is_break] => 1
)
[4] => stdClass Object
(
[question_id] => 17
[is_break] => 1
)
)
如何通过is_break = 1拆分(分组)所以我有问题_id(13,14)(15,16)(17)
答案 0 :(得分:1)
一个简单而天真的解决方案可能看起来像这样:
var original = /* your original array, the one you posted */;
var result = [];
var tmp = [];
$.each(original, function(idx, obj) {
tmp.push(obj.question_id);
if(obj.is_break == 1) {
result.push(tmp);
tmp = [];
}
});
console.log(result); // returns array of array
HTH
编辑:在PHP中,它可能看起来像这样(我不太精通PHP):
var $original = /* your original array, the one you posted */;
var $result = [];
var $tmp = [];
foreach($original as $obj) {
$tmp.push($obj.question_id); /* or could be $obj['question_id'] */
if($obj.is_break == 1) { /* or could be $obj['is_break'] */
$result.push($tmp);
$tmp = [];
}
});
答案 1 :(得分:0)
这是解决方案
$data = {your data};
$result = array();
$i = 0;
foreach($data as $k => $item) {
if ($item->is_break) {
$result[] = array_slice($data, $i, $k);
}
$i = $k;
}
print_r($result);
答案 2 :(得分:0)
试试这个:
<?php
$inputArr = Array
(
Array("question_id" => 13, "is_break" => 0),
Array("question_id" => 14, "is_break" => 1),
Array("question_id" => 15, "is_break" => 0),
Array("question_id" => 16, "is_break" => 1),
Array("question_id" => 17, "is_break" => 1)
);
$result = array();
$tmp = array();
foreach ($inputArr as $obj) {
//$tmp . push($obj . question_id); /* or could be $obj['question_id'] */
array_push($tmp, $obj['question_id']);
if ($obj['is_break'] == 1) { /* or could be $obj['is_break'] */
//$result . push($tmp);
array_push($result, $tmp);
$tmp = array();
}
}
var_dump($result);
?>