0
$transport = array(
  "Car" => array('Volvo','BMW','Saab','Land Roover'),
  array("Air Plane"),
  "Boat" => array('Ship','Yacht','Sail Boat'), 
  array("Bicycle")
);

print_r($transport);
echo "<br/><br/><br/><br/>";

How can I write a function that will turn array $transport into array $transport_in_array? The goal is to wrap all elements of $transport inside an array so that the $transport_in_array becomes indexed.

$transport_in_array = array(
  array("Car" => array('Volvo','BMW','Saab','Land Roover')),
  array("Air Plane"),
  array("Boat" => array('Ship','Yacht','Sail Boat')),
  array("Bicycle")
);

print_r($transport_in_array);
1
  • $transport is indexed, it just has mixed key types. Commented May 6, 2020 at 16:04

2 Answers 2

2
$transport=array_map(function($k, $v) {
    return is_int($k) ? $v : array($k => $v);
}, array_keys($transport), $transport);
Sign up to request clarification or add additional context in comments.

Comments

1

Seems to it can be done in simple loop:

$transport = array(
  "Car" => array('Volvo','BMW','Saab','Land Roover'),
  array("Air Plane"),
  "Boat" => array('Ship','Yacht','Sail Boat'), 
  array("Bicycle")
);

$transport_in_array = array();
foreach ($transport as $key=>$value) {
    $transport_in_array[] = is_string($key) ? array($key => $value) : $value;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.