合并两个数组以创建关联数组

时间:2017-06-13 07:43:59

标签: php arrays json laravel associative-array

我有一个php数组,如下所示:

array:7 [▼
  "id" => 13
  "agent_id" => 1
  "reserved_by" => 1
  "vehicle_type" => "["Bus","Car"]"
  "no_of_vehicle" => "["2","1"]"
  "created_at" => "2017-06-13 05:46:49"
  "updated_at" => "2017-06-13 05:46:49"
]

此处,vehicle_typeno_of_vehicle采用json_encode格式。在上面的例子中,

json_decode我可以得到两个这样的数组

汽车类型

dd(json_decode($data->vehicle_type));

array:2 [▼
  0 => "Bus"
  1 => "Car"
]

no_of_vehicle

dd(json_decode($data->no_of_vehicle));

array:2 [▼
  0 => "2"
  1 => "1"
]

现在,我想要的是创建一个车辆类型和数字等于1的关联数组。

array:3 [▼
  Bus => "1"
  Bus => "1"
  Car => "1"
]

因为你所说的所有因为独特的钥匙而不可能。但是,是否可以使用嵌套的类似数组:

array:3 [▼
    array:1 [▼
      Bus => "1"
    ]

    array:1 [▼
      Bus => "1"
    ]

    array:1 [▼
      Bus => "1"
    ]
]

这对我来说没问题 不知道,我正在使用laravel 5.3

由于

2 个答案:

答案 0 :(得分:2)

array:3 [▼
  Bus => "1"
  Bus => "1"
  Car => "1"
]

这是不可能的,因为键必须是唯一的

你可以进入

["Bus", "Bus", "Car"]

["Bus" => 2, "Car" => 1]

回答更新的问题

你可以这样做:

$array = [
            "id" => 13,
            "agent_id" => 1,
            "reserved_by" => 1,
            "vehicle_type" => array("Bus", "Car"),
            "no_of_vehicle" => array("2", "1"),
            "created_at" => "2017-06-13 05:46:49",
            "updated_at" => "2017-06-13 05:46:49",
        ];

        $result = [];

        foreach ($array["vehicle_type"] as $key => $vehicle) {
            $num = intval($array["no_of_vehicle"][$key]);
            for ($i = 1; $i <= $num; $i++) {
                $result[] = array($vehicle => "1");
            }
        }

$result将是:

array:3 [▼
  0 => array:1 [▼
    "Bus" => "1"
  ]
  1 => array:1 [▼
    "Bus" => "1"
  ]
  2 => array:1 [▼
    "Car" => "1"
  ]
]

答案 1 :(得分:0)

我会创建一个这样的数组:

array[
  {
    vehicle_type => 'Bus',
    no_of_vehicle => 2,
  },
  {
    vehicle_type => 'Car',
    no_of_vehicle => 1,
  }
]

array['Bus_1', 'Bus_2', 'Car_1']