简体   繁体   中英

PHP Array of Objects with reference

I know how to do this in javascript using the following code

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?

This PHP code would do the same as your script:

$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.

$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.

$array = [];

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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