简体   繁体   English

如何将元素放入 php 中的 object 数组中?

[英]How to put elements in an object array in php?

How to put new elements in an object array in php, I made some code but it is not working.如何将新元素放入 php 的 object 数组中,我编写了一些代码,但它不起作用。 Here is my code:这是我的代码:

<?php
class DNA{

    private $RSID;
    private $CHROMOSOME;

    public function setRSID($RSID){
        return $this->RSID = $RSID;
    }

    public function setCHROMOSOME($CHROMOSOME){
        return $this->CHROMOSOME = $CHROMOSOME;
    }

    public function getRSID(){
      return $this->RSID;
    }
    public function getCHROMOSOME(){
      return $this->CHROMOSOME;
    }
}

$dna1[] = new DNA;

$dna1[0]->setRSID(1);
$dna1[0]->setCHROMOSOME(2);

$dna1[1]->setRSID(5);
$dna1[1]->setCHROMOSOME(3);

$dna1[2]->setRSID(7);
$dna1[2]->setCHROMOSOME(0);

?>

I do not know the correct syntax, I tried to find in the google, but I am not found a good solution.我不知道正确的语法,我试图在谷歌中找到,但我没有找到一个好的解决方案。 Someone can help me?有人可以帮助我吗?

Each time you run new DNA creates a single object, so if you want to have multiple objects you need to call it multiple times.每次运行new DNA时都会创建一个 object,因此如果您想要多个对象,则需要多次调用它。

In your case, you're just running it once: $dna1[] = new DNA;在您的情况下,您只需运行一次: $dna1[] = new DNA; creates a single object, and adds it to an array.创建单个 object,并将其添加到数组中。

To create three objects, you could do this:要创建三个对象,您可以这样做:

// First create an empty array
$dna1 = [];

// Now add objects to it one by one
$dna1[0] = new DNA;
$dna1[0]->setRSID(1);
$dna1[0]->setCHROMOSOME(2);

$dna1[1] = new DNA;
$dna1[1]->setRSID(5);
$dna1[1]->setCHROMOSOME(3);

$dna1[2] = new DNA;
$dna1[2]->setRSID(7);
$dna1[2]->setCHROMOSOME(0);

Hy you can try with associative array你可以尝试使用关联数组

php.net/manual/en/language.types.array.php php.net/manual/en/language.types.array.php

The result is like this,结果是这样的,

$dna = new DNA();
$dna_array[0]['rsid'] = $dna->setRSID(1);
$dna_array[0]['chromsome'] = $dna->setCHROMOSOME(2);

$dna_array[1]['rsid'] = $dna->setRSID(5);
$dna_array[1]['chromsome'] = $dna->setCHROMOSOME(3);

$dna_array[2]['rsid'] = $dna->setRSID(7);
$dna_array[2]['chromsome'] = $dna->setCHROMOSOME(0);

var_dump($dna_array);
var_dump($dna_array[0]);
var_dump($dna_array[1]);
var_dump($dna_array[2]);
var_dump($dna_array);
var_dump($dna_array[0]['rsid']);
var_dump($dna_array[0]['chromsome']);

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

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