【问题标题】:How to Replace associative array key with custom key ..?如何用自定义键替换关联数组键..?
【发布时间】:2018-04-06 13:32:39
【问题描述】:

我需要以 'floorno' 和 'units' 作为键输出。但是在执行 array_splice 操作后,'floorno' 和 'units' 键被替换为整数值。

如何用文本 floorno 和 unit 替换整数值键。

下面是我的代码

          $floor = "Ground";
          $query = "SELECT id,property_no,status FROM property_details WHERE wing ='$A' AND floor ='$floor'";
          $execute = $db->query($query);
          $ground = $execute->fetchAll(PDO::FETCH_ASSOC);
          $block_A = array("floorno"=>$floor,"units"=>$ground);

          $floor = "First";
          $query = "SELECT id,property_no,status FROM property_details WHERE wing ='$A' AND floor ='$floor'";
          $execute = $db->query($query);
          $ground = $execute->fetchAll(PDO::FETCH_ASSOC);
          $first = array("floorno"=>$floor,"units"=>$ground);
          array_splice($block_A,2,0,$first);

下面是我的数组o/p:

   {
    "0": "Second",
    "1": [
         {
          "id": "396",
          "property_no": "SSC.A.02.01",
          "status": "0"
         },
         {
           "id": "397",
           "property_no": "SSC.A.02.02",
           "status": "0"
         }
],
"2": "First",
"3": [
       {
         "id": "388",
         "property_no": "SSC.A.01.01",
         "status": "0"
       },
       {
        "id": "389",
        "property_no": "SSC.A.01.02",
        "status": "0"
       }
],
"floorno": "Ground",
"units": [
    {
        "id": "379",
        "property_no": "SSC.A.00.01",
        "status": "0"
    },
    {
        "id": "381",
        "property_no": "SSC.A.00.02",
        "status": "0"
    }
]
}

【问题讨论】:

  • 你只需要这个 $block_A = array("floorno"=>$floor,"units"=>$ground); $result = array($block_A) 然后 $result[] = $first
  • 我只想以上述格式输出..

标签: php array-splice


【解决方案1】:

与关联拼接的辅助函数

    function array_splice_assoc(&$input, $offset, $length, $replacement)
    {
        $replacement = (array)$replacement;
        $key_indices = array_flip(array_keys($input));
        if (isset($input[$offset]) && is_string($offset)) {
            $offset = $key_indices[$offset];
        }

        if (isset($input[$length]) && is_string($length)) {
            $length = $key_indices[$length] - $offset;
        }

        $input = array_slice($input, 0, $offset, TRUE)
            + $replacement
            + array_slice($input, $offset + $length, NULL, TRUE);
    }

【讨论】:

    猜你喜欢
    • 2011-09-17
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多