Sagar Sagar -4 years ago 37
JSON Question

Merge two array to create an associative array

I have a

php
array something like this:

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"
]


Here,
vehicle_type
and
no_of_vehicle
are in
json_encode
format. In the above case,

By
json_decode
I can get two arrays like this

vehicle_type

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"
]


Now, what I want is to create an associative array of vehicle type and number equals 1.

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


It's impossible as all you say because of unique key. But, Is to possible to make similar array with nested like:

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

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

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


That will be fine for me
Any idea, I am using
laravel 5.3


Thanks

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

It's impossible, because the keys must unique

you can make it to

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

or

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

Answer to updated question

You can do like this:

$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");
            }
        }

the $result will be:

array:3 [▼
  0 => array:1 [▼
    "Bus" => "1"
  ]
  1 => array:1 [▼
    "Bus" => "1"
  ]
  2 => array:1 [▼
    "Car" => "1"
  ]
]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download