2015-11-18 77 views
0

對象數組我有對象的數組像這樣的例子:的foreach在PHP

[ 
    {"idroom":"3","idoption":"1","included":"0"}, 
    {"idroom":"3","idoption":"2","included":"0"}, 
    {"idroom":"3","idoption":"6","included":"1"}, 
    {"idroom":"3","idoption":"7","included":"1"}, 
    {"idroom":"3","idoption":"16","included":"0"}, 
    {"idroom":"3","idoption":"17","included":"0"} 
] 

,但如果我做了

foreach ($array_of_objects as $single) { 
    ... 
    fwrite($single->idroom) 
} 

我得到一個空文件...爲什麼?

編輯

要獲取對象的數組,我從javascript開始如下:

var dataAssociates = {}; 
var associatesRecords = []; 
dataAssociates = { "idroom": dataViewRooms.getItem(gridRooms.getSelectedRows()).roomId, 
    "idoption": $(this).find('input[name="option_name"]').attr('id'), 
    "included": (
      $(this).find('input[name="enabled_default"]').prop('checked') 
       ? '1' : '0') 
}; 
associatesRecords.push(dataAssociates); 
... 
$.ajax({.... , 'element' : JSON.stringify(associatesRecords) ,... }); 
+4

你真的有一個數組,或者你有一個json編碼的字符串,如你所示? –

+5

你真的做了'fwrite($ single-> idroom)'因爲這不起作用嗎否否 – PeeHaa

+2

看着這個,你可能需要將它從可能是Javascript對象數組轉換爲PHP可以使用的東西。需要更多信息。 – markdwhite

回答

0

沒關係,我想通了,我現在...我方纔做:

$data = json_decode(stripslashes($_REQUEST['element'])); 
foreach ($data as $single) { 
    $sql = "INSERT INTO .... VALUES ($single->idroom, $single->idoption, $single->included)"; 
    ... 
} 

所以它工作ED! 感謝大家!

乾杯! Luigi

0
$obj = new stdClass(); 
$obj->idroom = "3"; 

$obj->idoption = "1"; 
$obj->included = "0"; 
$array_of_objects[] = $obj; 

$obj->idoption = "2"; 
$obj->included = "0"; 
$array_of_objects[] = $obj; 

$obj->idoption = "6"; 
$obj->included = "1"; 
$array_of_objects[] = $obj; 

$obj->idoption = "7"; 
$obj->included = "1"; 
$array_of_objects[] = $obj; 

$obj->idoption = "16"; 
$obj->included = "0"; 
$array_of_objects[] = $obj; 

$obj->idoption = "17"; 
$obj->included = "0"; 
$array_of_objects[] = $obj; 

$filename = 'test.txt'; 
    $handle = fopen($filename, 'w'); 
if (!$handle) { 
    echo "Cannot open file ($filename)"; 
    exit; 
} 

foreach ($array_of_objects as $single) { 
    fwrite($handle, $single->idroom); 
} 
fclose($handle);