[英]PHP Array of Objects with reference
我知道如何使用以下代碼在javascript中執行此操作
var objectArray = [];
var cnt = 0;
while(cnt < 5) {
objectArray[cnt] = {};
objectArray[cnt]['field01'] = cnt;
objectArray[cnt]['field02'] = "Nothing";
cnt++;
}
我可以使用它來引用
console.log(objectArray[2]['field01']);
例如
有沒有在不使用類的情況下使用php的等效方法?
此PHP代碼將與您的腳本相同:
$objectArray = array();
$cnt = 0;
while($cnt < 5){
$objectArray[$cnt] = array(
'field01' => $cnt,
'field02' => 'Nothing'
);
$cnt++;
}
echo $objectArray[2]['field01'];
語法與Javascript非常相似,您無需使用對象。
$array = []; // Will work PHP 5.4+, otherwise use array();
$cnt = 0;
while($cnt < 5) {
$array[$cnt]['field01'] = $cnt;
$array[$cnt]['field02'] = 'Nothing';
cnt++;
}
要么...
$array = [];
for( $cnt=0; $cnt<5; $cnt++ ) {
$array[$cnt]['field01'] = $cnt;
$array[$cnt]['field02'] = 'Nothing';
}
編輯:有點混搭,如果從0開始遞增,則無需手動定義數組的索引。
$array = [];
for( $cnt=0; $cnt<5; $cnt++ ) {
$array[] = [
'field01' => $cnt,
'field02' => 'Nothing'
];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.