Frage

Is there anyway that an indexed array say ['1' => 'dave, '2' => 'ryan', '3' => 'mike', '4' => 'sam'] can be turned into an associative array. Which in this case would be ['dave' => 'ryan', 'mike' => 'sam'].

Obviously in the context and with the example i've given it doesn't make much sense but it would be helpful would just be handy to know.

All I can find on Google or here is ways of doing the opposite (associative -> indexed) unless I am completely missing an obvious answer.

War es hilfreich?

Lösung

This is the simplest way that I can think of for your example:

$arr = array('1' => 'dave', '2' => 'ryan', '3' => 'mike', '4' => 'sam');
$result = array();
$key = null;

foreach(array_keys($arr) as $k) {
    $v = $arr[$k];

    if($key === null) {
        $key = $v;
    } else {
        $result[$key] = $v;
        $key = null;
    }
}

Here's a demo.

Andere Tipps

$array = array('1' => 'dave', '2' => 'ryan', '3' => 'mike', '4' => 'sam');
$result = array();
for($i = 1; $i <= count($array); $i += 2) {
  $result[$array[$i]] = $array[$i+1];
}

Output

var_dump($result);
array(2) {
  ["dave"]=>
  string(4) "ryan"
  ["mike"]=>
  string(3) "sam"
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top