我在论坛上进行了搜索,确实找到了很多示例,但是没有人适合我。也许(肯定)我做错了什么。 因此,如果可能的话,我需要你们的帮助。
我想要什么? 我想从json文件中获取特定的数组。
数组:
array (
'Data' =>
array (
0 =>
array (
'Id' => 439201,
array (
),
'Members' =>
array (
0 =>
array (
'PortfolioId' => 439201,
'Id' => 100,
array (
'Id' => 1182,
'Symbol' => 'BTC',
),
'Amount' => 0.1,
'BuyPrice' => 4000,
),
1 =>
array (
'PortfolioId' => 439201,
'Id' => 200,
array (
'Id' => 1182,
'Symbol' => 'BTC',
),
'Amount' => 0.2,
'BuyPrice' => 5000,
)
)
)
)
)
我要这样打印:
+----------+---------+----------+
| id | amount | BuyPrice |
+-------------------------------+
| 100 | 0.1 | 4000 |
+-------------------------------+
| 200 | 0.2 | 5000 |
+----------+---------+----------+
我的php代码:
$url = file_get_contents(dirname(__DIR__ ) . '/json/history.json');
$array = json_decode($url, TRUE);
foreach ($array as $items) {
foreach ($items as $key => $value) {
echo $value['Id'] . '|' . $value['amount'] . '|' . $value['BuyPrice'] . '<br>';
}
}
答案 0 :(得分:1)
尝试一下
$arrayName = array (
'Data' =>
array (
0 =>
array (
'Id' => 439201,
array (
),
'Members' =>
array (
0 =>
array (
'PortfolioId' => 439201,
'Id' => 100,
array (
'Id' => 1182,
'Symbol' => 'BTC',
),
'Amount' => 0.1,
'BuyPrice' => 4000,
),
1 =>
array (
'PortfolioId' => 439201,
'Id' => 200,
array (
'Id' => 1182,
'Symbol' => 'BTC',
),
'Amount' => 0.2,
'BuyPrice' => 5000,
),
),
),
),
);
foreach ($arrayName['Data'][0]['Members'] as $key => $value) {
echo $value['Id'] . '|' . $value['Amount'] . '|' . $value['BuyPrice'] . '<br>';
}
答案 1 :(得分:1)
这应该剪下来:
$array = [
'Data' =>
[
[
'Id' => 439201,
[],
'Members' => [
[
'PortfolioId' => 439201,
'Id' => 100,
[
'Id' => 1182,
'Symbol' => 'BTC',
],
'Amount' => 0.1,
'BuyPrice' => 4000,
],
[
'PortfolioId' => 439201,
'Id' => 200,
[
'Id' => 1182,
'Symbol' => 'BTC',
],
'Amount' => 0.2,
'BuyPrice' => 5000,
]
]
]
]
];
foreach($array['Data'] as $value) {
foreach($value['Members'] as $member) {
echo "{$member['Id']}|{$member['Amount']}|{$member['BuyPrice']}<br>";
}
}
更新:如果要基于输出构建数组,则可以执行以下操作:
$map = array_map(function($data) {
return array_map(function($member) {
['Id' => $Id, 'Amount' => $Amount, 'BuyPrice' => $BuyPrice] = $member;
return compact('Id', 'Amount', 'BuyPrice');
}, $data['Members']);
}, $array['Data']);
print_r($map);