2017-04-19 69 views
1

我有一个叫Person的类,有他的get和set,我想知道如何从数据层返回一个List。在C#中我使用列表,我可以返回列表,但在PHP中,我不知道如何。在PHP中的对象列表

function AllPersons() 
{ 
    try 
    { 
     $objConn = new Connection(); 
     $conn = $objConn ->Connect(); 
     $sql = "SELECT * FROM PERSON"; 
     $answer= mysqli_query($cn, $sql); 
     if(mysqli_num_rows($answer) > 0) 
     { 
      while($row = mysqli_fetch_array($answer)) 
      { 
       /*here i want to do something like in C# 
        List<Person>listPerson; 
        listPerson.add(objPerson);*/ 
      } 
     } 
     else 
     { 
      return null; 

     } 
    } 
    catch (Exception $e) 
    { 
     //FB::log("nada"); 
    } 
} 
+0

你的意思是你想返回一个[数组](http://www.php.net/manual/en/language.types.array.php)? –

回答

2

创建数组并填充它。

listPerson = []; 
while($row = mysqli_fetch_array($answer)) { 
    listPerson[] = new Person($row); 
    } 
+0

谢谢,它工作:) –

-1
function AllPersons() 
{ 
    try 
    { 
     $objConn = new Connection(); 
     $conn = $objConn ->Connect(); 
     $sql = "SELECT * FROM PERSON"; 
     $answer= mysqli_query($cn, $sql); 
     if(mysqli_num_rows($answer) > 0) 
     { 
      while($row = mysqli_fetch_array($answer)) 
      { 
       print_r($row); 
      } 
     } 
     else 
     { 
      return null; 

     } 
    } 
    catch (Exception $e) 
    { 
     //FB::log("nada"); 
    } 
} 
2

在PHP的数组代替使用列表/数组你在.NET中使用的。 当涉及到突变时,它们非常灵活。

在这种情况下,你可能接近它想:

... 

$persons = array(); 
while($row = mysqli_fetch_array($answer)) 
{ 
    // Using [] appends the content of $row to the $persons array. 
    $persons[] = $row; 
} 

... 

更多about the flexibility of PHPs arrays here

+0

谢谢,它工作。 –

1

列表是C#的量纲阵列(也可在三维中使用)。 PHP中的数组也是无量纲的。所以你可以使用数组。

... 
$listPerson = array(); 
while($row = mysqli_fetch_array($answer)) 
      { 
       $listPerson[] = objPerson; 
      } 
...