我想知道如何在php中创建这样的JSON数组......
WRITE_EXTERNAL_STORAGE
我知道它必须是我假设的某种多维数组?我尝试过像......
dangerous
但这似乎是一种可怕的方法,我正在做一些非常棒的事情。我真的想知道这样做的正确方法。
答案 0 :(得分:1)
理想情况下,您不会将名单和球员号码添加到键(roster1,player1等)。我使用数组键为我做这项工作。类似的东西:
$data['rosters'][] = [
['sport' => 'nfl', 'firstname' => 'Tyrod', 'lastname' => 'Taylor'],
['sport' => 'nfl', 'firstname' => 'Lamar', 'lastname' => 'Miller'],
];
$data['rosters'][] = [
['sport' => 'nfl', 'firstname' => 'Carson', 'lastname' => 'Palmer'],
['sport' => 'nfl', 'firstname' => 'David', 'lastname' => 'Johnson'],
];
echo json_encode($data);
那应该给你:
{
"rosters": [
[{
"sport": "nfl",
"firstname": "Tyrod",
"lastname": "Taylor"
}, {
"sport": "nfl",
"firstname": "Lamar",
"lastname": "Miller"
}],
[{
"sport": "nfl",
"firstname": "Carson",
"lastname": "Palmer"
}, {
"sport": "nfl",
"firstname": "David",
"lastname": "Johnson"
}]
]
}
以下是如何使用循环构建此数据结构的示例。
$data = [];
// ...for the example, but you'll want this to be your source data.
$number_of_rosters = 2;
$number_of_players = 2;
foreach (range(1, $number_of_rosters) as $index => $roster) {
foreach (range(1, $number_of_players) as $player) {
$data['rosters'][$index][] = ['sport' => 'nfl', 'firstname' => 'Tyrod', 'lastname' => 'Taylor'];
}
}