如何在PHP中解析这个复杂的数组?

时间:2013-09-26 07:55:59

标签: php multidimensional-array

我有这个结构来自数组转储:

0 => 
object(stdClass)[3]
  public 'start' => string '12:30:00' (length=8)
  public 'end' => string '12:45:00' (length=8)
  public 'structure' => 
    object(stdClass)[5]
      public 'structure_id' => int 5
      public 'structure_name' => string 'LABORATORY 1' (length=18)
  public 'specialist' => 
    object(stdClass)[6]
      public 'specialist_id' => int 222
      public 'specialist_surname' => string 'Smith' (length=7)
      public 'specialist_name' => string 'John' (length=9)
      public 'specialist_signature' => string 'Dr.' (length=3)
  public 'price' => float 80.5
1 => 
object(stdClass)[3]
  public 'start' => string '12:30:00' (length=8)
  public 'end' => string '12:45:00' (length=8)
  public 'structure' => 
    object(stdClass)[5]
      public 'structure_id' => int 5
      public 'structure_name' => string 'LABORATORY 4' (length=18)
  public 'specialist' => 
    object(stdClass)[6]
      public 'specialist_id' => int 222
      public 'specialist_surname' => string 'White' (length=7)
      public 'specialist_name' => string 'Jack' (length=9)
      public 'specialist_signature' => string 'Dr.' (length=3)
  public 'price' => float 80.5
2 => 
object(stdClass)[3]
  public 'start' => string '12:30:00' (length=8)
  public 'end' => string '12:45:00' (length=8)
  public 'structure' => 
    object(stdClass)[5]
      public 'structure_id' => int 5
      public 'structure_name' => string 'LABORATORY 9' (length=18)
  public 'specialist' => 
    object(stdClass)[6]
      public 'specialist_id' => int 222
      public 'specialist_surname' => string 'Brown' (length=7)
      public 'specialist_name' => string 'Lester' (length=9)
      public 'specialist_signature' => string 'Dr.' (length=3)
  public 'price' => float 80.5

如何用PHP解析它?特别是,我想将值分配给普通的PHP变量,以便打印它们或放入HTML表格。

2 个答案:

答案 0 :(得分:1)

您需要使用PHP上的extract()

<?php
$size = "large";
$var_array = array("color" => "blue",
                   "size"  => "medium",
                   "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");
echo "$color, $size, $shape, $wddx_size\n";
?>
  

输出:蓝色,大,球形,中等

答案 1 :(得分:1)

  

您可以像这样访问此结构

echo $object[0]->start;
echo $object[0]->end;
echo $object[0]->structure->specialist_id;
  

这将导致

12:30:00
12:45:00
5

为什么你需要这个变量?这将导致太多的变量。而是使用循环迭代对象并使用“ - &gt;”

访问内部对象