dongyigua4468
2014-05-05 16:33
浏览 1.0k

将对象添加到PHP数组

I'm trying to add an object while I'm declaring an array in PHP but I can't figure out the right syntax. Here's what i'm trying:

 $obr = [
    ["Office", "Orders", { role: "style" } ],       
    ["Jacksonville", 1254, "magenta"],
    ["Orlando", 653, "blue"],
    ["Sarasota", 789, "green"],
    ["Stuart", 468, "yellow"],
    ["Tampa", 982, "cyan"]
];

图片转代码服务由CSDN问答提供 功能建议

我正在尝试添加一个对象,而我在PHP中声明一个数组,但我无法弄清楚 正确的语法。 这是我正在尝试的:

  $ obr = [
 [“Office”,“Orders”,{role:“style”}],
 [“Jacksonville  “,1254,”magenta“],
 [”Orlando“,653,”blue“],
 [”Sarasota“,789,”green“],
 [”Stuart“,468,”yellow“]  ,
 [“Tampa”,982,“cyan”] 
]; 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duanshanduo3363 2014-05-05 16:39

    Replace { role: "style" } with (object)[role => "style"]. This will cast an associative array to stdClass

    评论
    解决 无用
    打赏 举报
  • duangan9251 2014-05-05 16:44

    You are declaring an array, if you want to add another array inside the first one, try something like this:

    $obj = array(
      array("Office", "Orders", array("role" => "style")),       
      array("Jacksonville", 1254, "magenta"),
      array("Orlando", 653, "blue"),
      array("Sarasota", 789, "green"),
      array("Stuart", 468, "yellow"),
      array("Tampa", 982, "cyan"));
    
    评论
    解决 无用
    打赏 举报
  • dongpin3794 2014-05-05 16:48

    You've posted JSON notation of an object (JavaScript).

    PHP language uses another syntax:

    $obj = array(
         array("Office", "Orders", array("role" => "style")),       
         array("Jacksonville", 1254, "magenta"),
         // ...
    );
    

    or (I prefer this one as more flexible)

    $obj = array();
    $obj[] = array("Office", "Orders", array("role" => "style"));
    $obj[] = array("Jacksonville", 1254, "magenta");
    // ...
    

    (When array is defined, you can use print_r($obj); to dump it and see its total structure.)

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题