代码之家  ›  专栏  ›  技术社区  ›  LeBlaireau

php-对象数组

  •  -3
  • LeBlaireau  · 技术社区  · 6 年前

    我来自一个javascript背景,我想做类似的事情。

    $questions = [
          {
           "title" => "this is the title",
           "description" => "this is the desctiption"
          },
          {
           "title" => "this is the title2",
           "description" => "this is the desctiption2"
          }
        ];
    

    如何在PHP中创建对象数组?

    3 回复  |  直到 6 年前
        1
  •  1
  •   MonkeyZeus    6 年前

    您的示例似乎是格式正确的JS数组/对象声明:

    var questions = [
      {
       "title" => "this is the title",
       "description" => "this is the desctiption"
      },
      {
       "title" => "this is the title2",
       "description" => "this is the desctiption2"
      }
    ];
    

    因此,在PHP中实现类似结果的最简单方法是:

    $questions = [
        [
            "title" => "this is the title",
            "description" => "this is the desctiption"
        ],
        [
            "title" => "this is the title2",
            "description" => "this is the desctiption2"
        ]
    ];
    
        2
  •  2
  •   AbraCadaver    6 年前

    使用标准对象的最快方法是创建数组并转换为对象:

    $questions = [
          (object)[
           "title" => "this is the title",
           "description" => "this is the desctiption"
          ],
          (object)[
           "title" => "this is the title2",
           "description" => "this is the desctiption2"
          ]
    ];
    

    或者,您可以JSON对数组进行编码和解码:

    $questions = [
          [
           "title" => "this is the title",
           "description" => "this is the desctiption"
          ],
          [
           "title" => "this is the title2",
           "description" => "this is the desctiption2"
          ]
    ];
    
    $questions = json_decode(json_encode($questions));
    

        3
  •  0
  •   WizardNx    6 年前

    这不是真正的“真”对象,因为只有属性。 这种结构最好作为简单的数组来处理,您的JS字符串可以很容易地转换成这样的数组:

    $questions = '[
        {
        "title" => "this is the title",
        "description" => "this is the desctiption"
        },
        {
        "title" => "this is the title2",
        "description" => "this is the desctiption2"
        }
    ]';
    
    $my_array = json_decode($questions, true);
    

    请注意,json_decode的真正参数将强制输出为关联数组。那么您的$my_数组将是:

    array(2)
    {
        [0]=>
        array(2) {
            ["title"]=>
            string(17) "this is the title"
            ["description"]=>
            string(23) "this is the desctiption"
        }
        [1]=>
        array(2) {
            ["title"]=>
            string(18) "this is the title2"
            ["description"]=>
            string(24) "this is the desctiption2"
        }
    }