繁体   English   中英

将关联数组传递给PHP中的另一个关联数组

[英]Passing an Associative array into another associative array in PHP

抱歉,这是一个简单的解决方法-我在PHP中传递一些数组时遇到问题。 我有两个数组设置,例如:

$person = array(
            'height' => 100,
            'build'  => "average",
            'waist'  => 38,
            );

$hobbies = array(
            'climbing' => true,
            'skiing'   => false,
            'waist'    => 38,
            );

现在,如果我在这些数组上执行print_r(),它们将按预期返回结果。然后将2个数组插入新数组,如下所示:

$total = array($person, $hobbies);

再次使用print_r返回一个包含两个数组的新数组,但它不是关联的。 但是,如果我尝试执行以下操作:

$total = array(
                'person'   <= $person,
                'hobbies'  <= $hobbies,
               );

我使用上面的代码在$ total上执行了一个print_r,但我没有看到两个数组都具有关联。 ^以上数据仅是示例数据,但在我的真实应用程序中结构相同,我得到以下结果:

Array ( [0] => 1 [1] => 1 )

如果我太胖了,我再次道歉-我有种感觉。

听起来您想要$total数组具有子数组的personhobbies密钥。 如果是这样,只需执行以下操作:

$total = array("person" => $person, "hobbies" => $hobbies);

输出示例:http: //3v4l.org/5U5Hh

您的数组分配方式错误: 'person' <= $person应该是'person' => $person

// Wrong
$total = array(
  'person' <= $person,
  'hobbies' <= $hobbies,
);

// Right
$total = array(
  'person' => $person,
  'hobbies' => $hobbies,
);

如果要将两个数组合并为一个新数组,则需要使用array_merge。

$result = array_merge($person, $hobbies);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM