1

这可能太明显了,但我现在有点脑死了。

$sizeArr = array({
                    "name"=>'18"x24"',"wd"=>18,"ht"=>24,"price"=>99.00
                },
                {
                    "name"=>'24"x36"',"wd"=>24,"ht"=>36,"price"=>189.00
                });

我希望它可以被访问$sizeArr[0]->name,但我收到一条错误消息Unexpected {

我究竟做错了什么?

4

4 回答 4

3

您不能{}像在 JavaScript 中那样在 PHP 中定义对象(我假设您对此很熟悉)。

在 PHP 中,对象和数组都是arrays - 是的,如果您要序列化为 JSON,这确实会带来问题。

所以:

$sizeArr = array(array(
    "name"=>'18"x24"',"wd"=>18,"ht"=>24,"price"=>99.00
),
array(
    "name"=>'24"x36"',"wd"=>24,"ht"=>36,"price"=>189.00
));
于 2013-04-28T14:02:20.153 回答
0

您必须转换您的数组:

$yourArray = array (
   'item1' => 'Apple',
   'item2' => 'Peach'
);

$p = (object) $yourArray;
print $p->item1;

对于多维数组,请看这里:http ://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass

于 2013-04-28T14:06:32.143 回答
0

你不能用{}这个,但你可以试试这个

(object)用于转换arrayobject

 $sizeArr = array(
     (object)array(
       "name"=>'18"x24"',"wd"=>18,"ht"=>24,"price"=>99.00
     ),
     (object)array(
      "name"=>'24"x36"',"wd"=>24,"ht"=>36,"price"=>189.00
     )
 );
 echo $sizeArr[0]->name;

$sizeArr结构 print_r($sizeArr);输出

 Array
(
    [0] => stdClass Object
    (
        [name] => 18"x24"
        [wd] => 18
        [ht] => 24
        [price] => 99
    )

    [1] => stdClass Object
    (
        [name] => 24"x36"
        [wd] => 24
        [ht] => 36
        [price] => 189
    )

)

输出:

18"x24"
于 2013-04-28T14:18:35.290 回答
0
    $sizeArr = array(
                    (object)array("name"=>'18"x24"',"wd"=>18,"ht"=>24,"price"=>99.00),
                    (object)array("name"=>'24"x36"',"wd"=>24,"ht"=>36,"price"=>189.00)
                    );



    $sizeArr[0]->name;
于 2013-04-28T14:18:41.190 回答