Question

so I have an array similar to this

$arr[0]['name'] = 'Name';
$arr[0]['id'] = 2382;

$arr[1]['name'] = 'Name';
$arr[1]['id'] = 2838;

$arr[2]['name'] = 'Name';
$arr[2]['id'] = 2832;

How could I reformat the array replacing the initial index (0, 1, 2) with the id value of the array? Is this possible? The final array would be like this

$arr[1922]['name'] = 'Name';
$arr[2929]['name'] = 'Name';
$arr[3499]['name'] = 'Name';

Thanks

Was it helpful?

Solution

This is fairly straightforward.

It's simply a case of looping over the original array and building the new one as you go along.

Once you've finished you can, if you want, replace the new array with the old one.

foreach ( $arr as $thisArray ) {
  $aNewArray[ $thisArray['id']]['name'] = $thisArray['name'];
}
$arr = $aNewArray;

If you have an arbitrary number of elements in the array and you just want to wipe out the ID and keep the rest you can unset the ID as you go along and use the resulting array:

foreach ( $arr as $thisArray ) {
  $id = $thisArray['id'];
  unset( $thisArray['id'] );
  $aNewArray[ $id ] = $thisArray;
}
$arr = $aNewArray;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top