PHP阵列的正确逻辑

时间:2019-02-13 14:42:28

标签: php arrays

我需要产生这样的输出:

{
  "properties": [
   {
     "name": "name",
     "value": "A company name"
   },
   {
     "name": "description",
     "value": "A company description"
    }
  ]
}

我已经这样写了逻辑:

$data = array(
    "properties" => array(
        "name" => "name", 
        "value" => $companyname,
        "name" => "address", 
        "value" => $AddressLine1,
        "name" => "address2", 
        "value" => $AddressLine2,
        "name" => "address3", 
        "value" => $AddressLine3,
        "name" => "locality", 
        "value" => $Locality,
        "name" => "city", 
        "value" => $Town,
        "name" => "state", 
        "value" => $County,
        "name" => "zip", 
        "value" => $PostCode,
        "name" => "country", 
        "value" => $Country,
        "name" => "phone", 
        "value" => $Telephone,
        "name" => "domain", 
        "value" => $Website,
        "name" => "lead_forensics_business_id", 
        "value" => $hubspotcompanyid
    )
); 

有人可以突出显示产生上述输出的正确方法吗?

3 个答案:

答案 0 :(得分:1)

每个namevalue对应该是它们自己的数组。像这样:

$data = [
    "properties" => [
        [
            "name"  => "name", 
            "value" => $companyname,
        ],
        [
            "name"  => "address", 
            "value" => $AddressLine1,
        ],

        // And so on
    ]
];

(我选择了创建数组[]而不是array()的简写,因为我认为它更易于阅读)。

答案 1 :(得分:0)

如果我没记错的话,这应该可以解决问题:

$data = array(
  "properties" => array(
    array(
      "name" => "name",
      "value" => $companyname
    ),
    array(
      "name" => "address",
      "value" => $AddressLine1
    ),
    ...
  )
);

PHP会根据内容自动构建{}或[]。 因此,您只需使用array()函数即可构建整个结构。

答案 2 :(得分:-1)

类似这样的事情...

$data = array();
array_push($data, array('name' => 'name', 'value' => $companyname));
array_push($data, array('name' => 'address', 'value' => $AddressLine1));
array_push($data, array('name' => 'address2', 'value' => $AddressLine2));

$output = array();
$output['properties'] = $data;

echo json_encode($output);