2015-09-25 128 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

你需要內部轉換代碼嗎? –