我希望在单独的数组中从下面的JSON中获取invoices
。
[
{
"id":1,
"name":"Demo Name",
"email":"info@demo.com",
"mobile":"881730344",
"mobilealt":"78693446777",
"gender":"male",
"address":"102a sdf",
"description":"Super admin role and super admin permissions",
"profileimage":"profileimage\/team1.jpg",
"status":"active",
"created_at":null,
"updated_at":"2016-06-29 17:08:24",
"deleted_at":null,
"under_id":0,
"assign_at":"2016-05-11 10:41:50",
"children":[
{
"id":17,
"under_id":1,
"name":"Some Name",
"children":[
{
"id":35,
"under_id":17,
"name":"test sub user ",
"children":[
],
"invoices":[
]
},
{
"id":36,
"under_id":17,
"name":"Harsh",
"children":[
],
"invoices":[
]
}
],
"invoices":[
]
},
{
"id":18,
"under_id":1,
"name":"Demo Demo Sname",
"children":[
],
"invoices":[
{
"order_id":31,
"sum":161500,
"month":"May",
"user_id":18
}
]
},
{
"id":20,
"under_id":1,
"name":"Divya",
"children":[
],
"invoices":[
]
},
{
"id":25,
"under_id":1,
"name":"Dhiraj",
"children":[
{
"id":19,
"under_id":25,
"name":"New user",
"children":[
{
"id":33,
"under_id":19,
"name":"Demo Sub Sub user",
"children":[
],
"invoices":[
]
}
],
"invoices":[
{
"order_id":32,
"sum":40000,
"month":"July",
"user_id":19
}
]
}
],
"invoices":[
]
}
]
}
]
我正在考虑递归循环。但我尝试了下面的方法,似乎没有工作。
public function take_invoices($array){
static $arrinvoices = [];
foreach($array as $item){
if(count($item->invoice) > 0){
dd($item->invoice); //------------->Laravel function to die and dump. its always empty
$arrinvoices[] = $item->invoice;
}
if(count($item->children) > 0){
$this->take_invoices($item->children);
}
}
return $arrinvoices;
}
谢谢! (提前!)
答案 0 :(得分:2)
使用preg_match_all
和preg_replace
函数的解决方案:
// $json_data - is your initial json string
// the next step takes all non-empty 'invoices'
preg_match_all("/\"invoices\":\[([^]]+)\]/", preg_replace("/\f|\v|\h|\t|\s+/", "", $json_data), $matches);
$invoices = [];
if (!empty($matches) && isset($matches[1])) {
$invoices = json_decode("[" . implode(",", $matches[1]) . "]", true);
}
print_r($invoices);
输出:
Array
(
[0] => Array
(
[order_id] => 31
[sum] => 161500
[month] => May
[user_id] => 18
)
[1] => Array
(
[order_id] => 32
[sum] => 40000
[month] => July
[user_id] => 19
)
)