2011-06-30 48 views
1

如果我的json_encode輸出是這樣的。我想輸出json_encode數組到javascript數組

[{"id":"nameid","src":"http#"},{"id":"nameid","src":"http#"}] 

我怎麼會變成這樣的:

[["name1","address1"],["name2","address2"]] 
+0

除了從一個陣列有兩個成員,這兩個數據結構似乎沒有任何共同之處,因此沒有合理的方式來執行轉換。 – Quentin

回答

0

假設你的意思是name1是從第一個對象的值​​3210,等...

其轉換爲陣列格式你想在傳遞給json_encode()之前。像這樣的東西可能會爲你工作:

// Assuming your objects are an array $objects 
$output_array = array(); 
foreach ($objects as $o) { 
    // Put the two properties from the object into an array 
    // and append it to $output_array 
    $output_array[] = array($o->id, $o->src); 
} 

// Encode the array as json 
$json = json_encode($output_array); 
1
var obj, result, source, _i, _len; 
    source = [ 
    { 
     "id": "nameid", 
     "src": "http#" 
    }, { 
     "id": "nameid", 
     "src": "http#" 
    } 
    ]; 
    result = []; 
    for (_i = 0, _len = source.length; _i < _len; _i++) { 
    obj = source[_i]; 
    result.push([obj.id, obj.src]); 
    } 

(這是由CoffeeScript中產生的CoffeeScript源FYI要小得多。)

source = [{"id":"nameid","src":"http#"},{"id":"nameid","src":"http#"}] 
result = [] 
result.push([obj.id, obj.src]) for obj in source