2014-04-02 22 views
-1

我正在使用bigCommerece API檢索以下數組,它是產品的選項列表。使用echo $curlProductOptions我看到以下顯示在屏幕上:在PHP中通過一個數組循環不能按預期工作

[ 
    { 
     "id": 412, 
     "option_id": 37, 
     "display_name": "testSteveMemory", 
     "sort_order": 0, 
     "is_required": true 
    }, 
    { 
     "id": 413, 
     "option_id": 34, 
     "display_name": "Hard Drive (desktop)", 
     "sort_order": 1, 
     "is_required": true 
    }, 
    { 
     "id": 414, 
     "option_id": 24, 
     "display_name": "Include Keyboard & Mouse", 
     "sort_order": 2, 
     "is_required": true 
    }, 
    { 
     "id": 415, 
     "option_id": 33, 
     "display_name": "Memory", 
     "sort_order": 3, 
     "is_required": true 
    } 
] 

所以我假設我有含有上述數據內$curlProductOptions陣列。

我現在需要遍歷每個元素和echo每個'option_id'。

我曾嘗試:

foreach($curlProductOptions['option_id'] as $value) 
{echo $value;} 

和:

for ($i = 0; $i < count($curlProductOptions); ++$i) 
{echo 'optionID ='.$curlProductOptions[$i].option_id.'<br>';} 

我也嘗試了呼應的要素之一。

echo $curlProductOptions['option_id'][0]; 
echo $curlProductOptions[0]['option_id']; 

我在這裏不理解什麼?

+5

這看起來像一個* JSON編碼字符串*,而不是一個PHP數組。你必須'json_decode'它。 – deceze

回答

1

這對我工作得很好:

$curlProductOptions = json_decode($curlProductOptions, true); 
foreach($curlProductOptions as $value){ 
    echo $value['option_id']; 
} 
+0

謝謝你們。每個答案都是正確的選擇正確答案的正確答案是什麼,並且我只對每個有用答案+1? – user3193843

3

你有json編碼的字符串。所以你首先需要json_decode

嘗試這樣的:

$curlProductOptions = json_decode($curlProductOptions,true);//create associative array 
foreach($curlProductOptions['option_id'] as $value){ 
    echo $value; 
} 
+0

這隻適用於新的PHP版本嗎?在5.3它不起作用 – Dinistro