我正在上课,我尝试使用json_encode输出它,但变量不会改变。
PHP:
<?php
class person {
public $person = "";
}
class name {
public $lastname = "";
public $firstname = "";
}
$user = new person();
$user->person = new name();
$user->lastname = "Foo";
$user->firstname = "Bar";
echo json_encode($user);
?>
输出:
{&#34;人&#34; {&#34;姓&#34;:&#34;&#34;&#34;姓名&#34;:&#34;&#34;} &#34;姓&#34;:&#34;富&#34;&#34;姓名&#34;:&#34;酒吧&#34;}
预期输出:
{&#34;人&#34; {&#34;姓&#34;:富&#34;&#34;&#34;姓名&#34;:&#34;酒吧&#34;} }
有人可以向我解释为什么它不会改变吗?
答案 0 :(得分:2)
要设置$user
的名称,不应该打电话:
$user->person->firstname = "Foo";
$user->person->lastname = "Bar";
或者,您也可以在name
person
之前设置变量$name = new name();
$name->firstname = "Foo";
$name->lastname = "Bar";
$user->person = $name;
class person {
public $firstname;
public $lastname;
}
$user = new person();
$user->firstname = "Foo";
$user->lastname = "Bar";
echo json_encode(array('person' => $user));
修改
如果您只想要一个类,并且想要复制预期的输出:
- (void)addConstraintWithListNavigationViewController:(UIView *)listViewNavigation y:(CGFloat)y height:(CGFloat)height
{
//WIDTH_ListTableView = 0.4
//set x = 0;
NSLayoutConstraint *constraintToAnimate1 = [NSLayoutConstraint constraintWithItem:listViewNavigation
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:0.00
constant:0];
[self.view addConstraint:constraintToAnimate1];
//set y = y;
NSLayoutConstraint *constraintToAnimate2 = [NSLayoutConstraint constraintWithItem:listViewNavigation
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:0.00
constant:y];
[self.view addConstraint:constraintToAnimate2];
//set Width = self.view.frame.size.width*0.4
NSLayoutConstraint *constraintToAnimate3 = [NSLayoutConstraint constraintWithItem:listViewNavigation
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeWidth
multiplier:1-WIDTH_ListTableView
constant:0.0];
[self.view addConstraint:constraintToAnimate3];
//Set height = height
NSLayoutConstraint *constraintToAnimate4 = [NSLayoutConstraint constraintWithItem:listViewNavigation
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:0.00
constant:height];
[self.view addConstraint:constraintToAnimate4];
}
答案 1 :(得分:0)
更改这些行
$user->lastname = "Foo";
$user->firstname = "Bar";
要
$user->person->lastname = "Foo";
$user->person->firstname = "Bar";
你永远不会分配这些属性,这就是为什么它们在你的字符串中是空的。相反,您将它们分配给user
而不是name
,这就是您在编码name
之后看到它们的原因。
严格说来,这不应该被允许工作,你应该得到一个严格的警告。
答案 2 :(得分:0)
name
课程已分配到$user->person
。
因此,当您在firesname
课程中为lastname
和name
分配值时,您应使用以下代码
$user->person->lastname="Foo";
$user->person->firstname="Bar";
或
firstname
类中的lastname
和name
变量被视为新数据