我有一个多维数组,里面有3个数组。请参阅下面我的最小可运行示例:
<?php
$array1 = array("Bitcoin", "Ethereum", "Bitcoin Cash");
$array2 = array("BTC", "ETH", "BTC");
$array3 = array("10000", "3000", "6666");
//Multi Dimensional Array
$multi = array($array1, $array2, $array3);
print_r($multi);
foreach($multi as $k =>$a){
$multi[$k] = json_decode(json_encode($a));
}
print_r($multi);
// $json_data = json_encode($multi);
file_put_contents('data/myfile.json', $multi);
但是,我在输出文件中得到以下输出:
ArrayArrayArray
如何获取如下数据的任何建议:
{
"Bitcoin",
"BTC",
"10000"
},
{
"Ethereum",
"ETH",
"3000"
},
{
"Bitcoin Cash",
"BTC",
"6666"
},
答案 0 :(得分:1)
{
"Bitcoin",
"BTC",
"10000"
},
{
"Ethereum",
"ETH",
"3000"
},
{
"Bitcoin Cash",
"BTC",
"6666"
},
是无效的JSON格式。 &#39; {&#39;和&#39;}&#39;意味着它的地图(对象),所以必须有&#39; key:value&#39;行如:
{
0: "Bitcoin"
}
阵列使用的正确JSON&#39; [&#39;和&#39;]&#39;。
<?php
$array1 = array("Bitcoin", "Ethereum", "Bitcoin Cash");
$array2 = array("BTC", "ETH", "BTC");
$array3 = array("10000", "3000", "6666");
//Multi Dimensional Array
$multi = array();
foreach($array1 as $key => $v) {
$multi[] = [$array1[$key], $array2[$key], $array3[$key]];
}
file_put_contents('data/myfile.json', json_encode($multi));
产地:
[["Bitcoin","BTC","10000"],["Ethereum","ETH","3000"],["Bitcoin Cash","BTC","6666"]]
格式化:
[
[
"Bitcoin",
"BTC",
"10000"
],
[
"Ethereum",
"ETH",
"3000"
],
[
"Bitcoin Cash",
"BTC",
"6666"
]
]
答案 1 :(得分:1)
首先,您的预期结果无效json。它应该是数组{}
而不是$array1 = array("Bitcoin", "Ethereum", "Bitcoin Cash");
$array2 = array("BTC", "ETH", "BTC");
$array3 = array("10000", "3000", "6666");
$new = [];
// Restructure your array to get one item from each array
foreach ($array1 as $index => $value) {
$new[] = [
$value,
$array2[$index],
$array3[$index]
];
}
$multi = json_encode($new);
。
以下是如何根据需要格式化数据的方法 但是,它假定三个数组的长度始终相等:
[
[
"Bitcoin",
"BTC",
"10000"
],
[
"Ethereum",
"ETH",
"3000"
],
[
"Bitcoin Cash",
"BTC",
"6666"
]
]
这将产生您想要的格式,但是采用有效的json格式:
Stripe.apiKey = stripeApiKey;
Customer customer = Customer.retrieve(customerId);
Map<String, Object> cardParams = new HashMap<String, Object>();
cardParams.put("number", "4242424242424242");
cardParams.put("exp_month", "12");
cardParams.put("exp_year", "2018");
cardParams.put("cvc", "314");
Map<String, Object> tokenParams = new HashMap<String, Object>();
tokenParams.put("card", cardParams);
Token cardToken = Token.create(tokenParams);
Map<String, Object> sourceParams = new HashMap<String, Object>();
sourceParams.put("source", cardToken.getId()); //?
Card source = (Card) customer.getSources().create(sourceParams);
logger.info("Card created: " + source.toString());