1

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
)
treyBake
  • 6,440
  • 6
  • 26
  • 57
KunKun
  • 67
  • 1
  • 9
  • 4
    `$cs[get_cat_ID($c)] = $c;` ? – Cid Dec 04 '18 at 08:33
  • 2
    `$cs [] .=` makes little sense to begin with, `.=` is for string concatenation. `$cs[] =` would be the correct way to add new entries to a numeric array - but you want to specify the associative key here, so you must actually do that - `$cs['somekey'] =` – misorude Dec 04 '18 at 08:33
  • this is function in wordpress to get id from categoy name – KunKun Dec 04 '18 at 08:34
  • Is `get_cat_ID()` the source of the associative key? – Carl Binalla Dec 04 '18 at 08:36
  • Related: [Replace keys in an array based on another lookup/mapping array](https://stackoverflow.com/a/71274431/2943403) – mickmackusa Apr 17 '23 at 21:25

3 Answers3

4

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);
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
1

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
)
treyBake
  • 6,440
  • 6
  • 26
  • 57
Manoj Singh
  • 253
  • 1
  • 7
0
<?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);
pr1nc3
  • 8,108
  • 3
  • 23
  • 36