我有这种类型的数组
Array
(
[0] => Samy Jeremiah,55
[1] => Nelson Owen,93
[2] => McMaster Ashlie,88
[3] => Marsh Harlow,97
[4] => Macfarquhar Aiden,95
[5] => Lowe Sophie,91
);
我需要将此数组转换为以下类型的json
data: [
['Samy Jeremiah',55 ],
['Nelson Owen',93 ],
['McMaster Ashlie',88 ] ,
['Marsh Harlow',97 ] ,
['Macfarquhar Aiden',95 ],
['Lowe Sophie',91 ]
]
答案 0 :(得分:0)
试试这个
<?php
$yourArray = array(
'0' => 'Samy Jeremiah,55',
'1' => 'Nelson Owen,93',
'2' => 'McMaster Ashlie,88',
'3' => 'Marsh Harlow,97',
'4' => 'Macfarquhar Aiden,95',
'5' => 'Lowe Sophie,91',
);
#Check output 01
//print_r($yourArray);
foreach ($yourArray as $value) {
$explodeValue = explode( ',', $value );
$newName []= array($explodeValue[0] => $explodeValue[1]);
}
#Check output 02
//print_r($newName);
#Check output 03
echo(json_encode($newName));
?>
输出01
Array (
[0] => Samy Jeremiah,55
[1] => Nelson Owen,93
[2] => McMaster Ashlie,88
[3] => Marsh Harlow,97
[4] => Macfarquhar Aiden,95
[5] => Lowe Sophie,91
)
输出02
Array (
[0] => Array ( [Samy Jeremiah] => 55 )
[1] => Array ( [Nelson Owen] => 93 )
[2] => Array ( [McMaster Ashlie] => 88 )
[3] => Array ( [Marsh Harlow] => 97 )
[4] => Array ( [Macfarquhar Aiden] => 95 )
[5] => Array ( [Lowe Sophie] => 91 )
)
输出03
[
{"Samy Jeremiah":"55"},
{"Nelson Owen":"93"},
{"McMaster Ashlie":"88"},
{"Marsh Harlow":"97"},
{"Macfarquhar Aiden":"95"},
{"Lowe Sophie":"91"}
]
答案 1 :(得分:0)
您想要的结果是一个数组数组。您必须将数组的每个条目拆分为2个实体,并将它们作为数组推送到新数组中,然后将json_encode()推送到新数组中。
这个php-snippet只有在你的输入是一个字符串数组时才有效,它包含每个逗号作为name和int-value之间的分隔符:
$arr2 = array();
foreach($arr1 as $e) {
list($name, $val) = explode(',', $e);
$arr2[] = array($name, (int)$val);
}
echo json_encode($arr2);
答案 2 :(得分:0)
使用以下代码
$data = array('Samy Jeremiah,55', 'Nelson Owen,93', 'McMaster Ashlie,88', 'Marsh Harlow,97', 'Macfarquhar Aiden,95', 'Lowe Sophie,91');
$res = array();
foreach($data as $e) {
$list = explode(',', $e);
$res[] = array($list[0], $list[1]);
}
echo json_encode(['data'=>$arr2]);
<强>输出强>
{"data":[
["Samy Jeremiah",55],
["Nelson Owen",93],
["McMaster Ashlie",88],
["Marsh Harlow",97],
["Macfarquhar Aiden",95],
["Lowe Sophie",91]
]
}
答案 3 :(得分:-1)
使用json_encode
,您可以实现您想要的效果。
假设您的数组名称为$arr
,请立即应用json_encode
。
echo json_encode(array('data'=>$arr)); //your json will be print here
实时示例:
$arr = array('Samy Jeremiah,55', 'Nelson Owen,93', 'McMaster Ashlie,88', 'Marsh Harlow,97', 'Macfarquhar Aiden,95', 'Lowe Sophie,91');
$new_arr = array();
foreach($arr as $k => $val){
$na = explode(",", $val);
$na[0] = "'".$na[0]."'";
$value = implode(",", $na);
$new_arr[$k] = $value;
}
echo json_encode(array("data" => $new_arr));