KunKun
KunKun

Reputation: 67

How to change the key in associative array php

I have array like this:

Array (
   [0] => Aenean
   [1] => Lorem
   [2] => Morbi
)

I am try using foreach to make array above format be associative array. Trying to change the key (e.g. 0,1,2) to be another value (e.g. x,y,z).

array(
    'x' => 'Aenean',
    'y' => 'Lorem',
    'z' => 'Morbi'
),

So far, I try using foreach but give me wrong result

    $r_cat = array (Aenean,Lorem,Morbi);

    $cs = array();
    foreach ($r_cat as $c ) {
     $cs [] .= array (get_cat_ID($c) => $c);
    }
    print_r ($cs);

RESULT

Array (
   [0] => Array
   [1] => Array
   [2] => Array
)

Upvotes: 1

Views: 4259

Answers (3)

Manoj Singh
Manoj Singh

Reputation: 262

You can use PHP array_combine() function to set key from one array and values from the second array. No need to use the loop :

$a = array('x','y','z');
$b = array('Aenean','Lorem','Morbi');
$c = array_combine($a, $b);

echo '<pre>';print_r($c); echo '</pre>'; 

Result:

Array
(
    [x] => Aenean
    [y] => Lorem
    [z] => Morbi
)

Upvotes: 1

Mihai Matei
Mihai Matei

Reputation: 24276

You can use array_reduce

$array = ['Aenean', 'Lorem', 'Morbi'];

$array = array_reduce($array, function($carry, $item) {
    $carry[get_cat_ID($item)] = $item;

    return $carry;
}, []);

var_dump($array);

Upvotes: 4

pr1nc3
pr1nc3

Reputation: 8338

<?php
$array = array(
    0 => 'Aenean',
    1 => 'Lorem',
    2 => 'Morbi'
);

$i = 0;

$keyValues = array('x','y','z');

foreach ($array as $key => $value) {
    $cs[$keyValues[$i]] = $value;
    $i++;
}

echo '<pre>';
print_r($cs);

And the output is :

Array
(
    [x] => Aenean
    [y] => Lorem
    [z] => Morbi
)

I made a test array with some example values you want to put (x,y,z as you mentioned) and replaced your keys inside the foreach like you tried as well.

Another way is to use the key value in your foreach and replace it with the new one and after unset your old key like below:

<?php
$array = array(
    0 => 'Aenean',
    1 => 'Lorem',
    2 => 'Morbi'
);

$i = 0;

$keyValues = array('x','y','z');

foreach ($array as $key => $value) {
    $array[$keyValues[$i]] = $array[$key];
    unset($array[$key]);
    $i++;
}

echo '<pre>';
print_r($array);

Upvotes: 0

Related Questions