Javascript 数组格式转换为JSON格式
使用此数组值将其更改为JSON格式Javascript 数组格式转换为JSON格式,javascript,php,jquery,cakephp,Javascript,Php,Jquery,Cakephp,使用此数组值将其更改为JSON格式 $prices = array("250", "350", "400", "678", "800", "1000"); var opt = { milestones: { 1: { mlPos: 250, ---> (set $price value) mlId: false, mlClass: 'bi-custom', mlDim: '200%',
$prices = array("250", "350", "400", "678", "800", "1000");
var opt = {
milestones: {
1: {
mlPos: 250, ---> (set $price value)
mlId: false,
mlClass: 'bi-custom',
mlDim: '200%',
mlLabel: 'Milestone one',
mlLabelVis: 'hover',
mlHoverRange: 15,
mlLineWidth: 1
},
2: {
mlPos: 350, ---> (set $price value)
mlId: false,
mlClass: 'bi-custom',
mlDim: '200%',
mlLabel: 'Milestone two',
mlLabelVis: 'hover',
mlHoverRange: 15,
mlLineWidth: 1
},
3: {
mlPos: 400, ---> (set $price value)
mlId: false,
mlClass: 'bi-custom',
mlDim: '200%',
mlLabel: 'Milestone one',
mlLabelVis: 'hover',
mlHoverRange: 15,
mlLineWidth: 1
},
4: {
mlPos: 678,---> (set $price value)
mlId: false,
mlClass: 'bi-custom',
mlDim: '200%',
mlLabel: 'Milestone two',
mlLabelVis: 'hover',
mlHoverRange: 15,
mlLineWidth: 1
},
5: {
mlPos: 800,---> (set $price value)
mlId: false,
mlClass: 'bi-custom',
mlDim: '200%',
mlLabel: 'Milestone two',
mlLabelVis: 'hover',
mlHoverRange: 15,
mlLineWidth: 1
}
}
};
我们有一个数组格式的php变量$price
转换成javascript变量,就像这个json格式一样,问题不是将php变量转换成javascript变量,问题只是将php数组转换成json格式,就像上面的格式一样
有人请帮忙吗
谢谢。试试这个:
json_encode在php>5.2.0中提供:
echojson_encode($row);
在使用将数组强制转换为对象之前,还可以使用JSON\u FORCE\u OBJECT
选项:
$prices = array( "250", "350", "400", "678", "800", "1000" );
$row = [
'mlPos' => null,
'mlId' => false,
'mlClass' => 'bi-custom',
'mlDim' => '200%',
'mlLabel' => 'Milestone two',
'mlLabelVis' => 'hover',
'mlHoverRange' => 15,
'mlLineWidth' => 1
];
$rows = [];
foreach( $prices as $price ) {
$rows[] = (object) array_replace( $row, [ 'mlPos' => $price ] );
}
$opt = [ 'milestones' => (object) $rows ];
echo json_encode( $opt, JSON_FORCE_OBJECT );
// output {"milestones":{"0":{"mlPos":"250","mlId":false,"mlClass":"bi-custom", ...
请说明您在json中需要什么格式,以及需要从什么输入转换为json
JSON_PRETTY_PRINT
以上内容将满足您的要求。但对于提供答案,请解释清楚
我想你也使用CakePHP3.0
您可以从那里获得答案,或在实施之前使用此链接
请准确回答您的问题。查找@RiggsFolly是的,我尝试过,手动插入一些值,如mIId:false、MIClass:bi-custom等。在我看来,您似乎正在尝试在浏览器上运行PHP代码!PHP只在服务器上运行!Javascript在浏览器中运行!如果我在这里错了,你需要把你的问题说得更清楚clear@RiggsFolly已经提到变量转换不是问题,只需将php数组转换成json格式,现在是clearNo。您显示的代码没有上下文。这是一个PHP脚本吗?这是PHP脚本中的javascript片段吗?这是从浏览器中看到的javascript吗?我已经发送了数组值,我需要将该数组值转换为json的代码format@Karthik:上面一行将php数组转换为json对象。是否需要内部转换代码???是的,我需要代码将mlId:false等值添加到array@Danijiel谢谢,代码运行良好,我需要一点怀疑:)