简体   繁体   English

PHP对象数组与参考

[英]PHP Array of Objects with reference

I know how to do this in javascript using the following code 我知道如何使用以下代码在javascript中执行此操作

var objectArray = [];
var cnt         = 0;

while(cnt < 5) {
    objectArray[cnt] = {};
    objectArray[cnt]['field01'] = cnt;
    objectArray[cnt]['field02'] = "Nothing";
    cnt++;
}

which I can then reference using 我可以使用它来引用

console.log(objectArray[2]['field01']);

for example 例如

Is there an equivalent way to do this in php without using a class? 有没有在不使用类的情况下使用php的等效方法?

This PHP code would do the same as your script: 此PHP代码将与您的脚本相同:

$objectArray = array();
$cnt = 0;

while($cnt < 5){
    $objectArray[$cnt] = array(
        'field01'   => $cnt,
        'field02'   => 'Nothing'
    );
    $cnt++;
}

echo $objectArray[2]['field01'];

The syntax is very similar to Javascript and you don't need to use objects. 语法与Javascript非常相似,您无需使用对象。

$array = []; // Will work PHP 5.4+, otherwise use array();
$cnt = 0;

while($cnt < 5) {
    $array[$cnt]['field01'] = $cnt;
    $array[$cnt]['field02'] = 'Nothing';
    cnt++;
}

or... 要么...

$array = [];

for( $cnt=0; $cnt<5; $cnt++ ) {
    $array[$cnt]['field01'] = $cnt;
    $array[$cnt]['field02'] = 'Nothing';
}

Edit: A bit of a mashup, there's no need to manually define the index of your array if it's starting from 0 and incrementing. 编辑:有点混搭,如果从0开始递增,则无需手动定义数组的索引。

$array = [];

for( $cnt=0; $cnt<5; $cnt++ ) {
    $array[] = [
        'field01' => $cnt,
        'field02' => 'Nothing'
    ];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM