2015-09-25 125 views
3

使用此数组值将其更改为JSON格式。将数组格式转换为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%', 
     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格式像上面格式。

任何人都请帮忙

谢谢。

+0

查找[json_encode](http://php.net/manual/en/function.json-encode.php) – RiggsFolly

+0

@RiggsFolly是的,我试过了,手动插入一些像mIId的值:false,MIClass:bi-custom etc. – karthik

+0

它看起来像我想你想在浏览器上运行PHP代码! PHP只能在服务器上运行! Javascript在浏览器中运行!如果我在这里错了,你将需要让你的问题**更清楚** – RiggsFolly

回答

1

在你使用json_encode投阵列为对象,你也可以使用该选项JSON_FORCE_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", ... 
+0

@Danijiel感谢代码工作正常,小疑问我需要:) – karthik

-3

试试这个:

json_encode在PHP可用> 5.2.0:

echojson_encode($row); 
+0

我发送数组值我需要代码来将该数组值转换为此JSON格式 – karthik

+0

@Karthik:上面的行将您的php数组转换为json对象。 –

+0

你需要内部转换代码吗? –