0

If I have an array $array like this:

Array ( 
    [0] => Array ( 
        [id] => 11 
        [name] => scifi 
        ) 
    [1] => Array (
         [id] => 12 
         [name] => documetary 
     ) 
    [2] => Array ( 
        [id] => 10 
        [name] => comedy 
    ) 
)

How could I turn it into simply:

Array ( 11, 12, 10 ) with no key value pairs.

I am trying to extract only the id from each array and add them into 1 array. I am trying it with a foreach;

$ids = [];

if ( $array ) {
  foreach ( $array as $item ) {
    $ids[] = $term->id;
  }
}

print_r($ids);

It just returns 3 empty arrays Array ( [0] => [1] => [2] => )

CyberJ
  • 1,018
  • 1
  • 11
  • 24
  • 3
    You don't need to loop yourself, you can just use https://www.php.net/manual/en/function.array-column.php – CBroe Nov 18 '21 at 08:22
  • @CBroe thanks that is a cool function! but it still returns more arrays `Array ( [0] => 11 [1] => 12 [2] => 10 ) ` instead just the ids in 1 array. Now i should loop over that? – CyberJ Nov 18 '21 at 08:25
  • you seem to be confused, `array_column()` returns ONE array with three key-value pairs - i.e. result as expected _the ids in 1 array_. – berend Nov 18 '21 at 08:31
  • @berend i am trying to get an array with the ids without the keys – CyberJ Nov 18 '21 at 08:35
  • 1
    an array will [always](https://www.php.net/manual/en/language.types.array.php) have 1 or more key-value pairs. maybe you actually need a string: `"11, 12, 10"`? or an array with one key-value pair: `[0] => "11, 12, 10"`? – berend Nov 18 '21 at 08:39
  • 1
    `$array = array_column($array, 'id');` or `$string = implode(', ', array_column($array, 'id'));` – cottton Nov 18 '21 at 09:10

1 Answers1

1

Using a loop, you can do this:

$arr1 = [
 ['id'=>11,'name'=>'scifi'],
 ['id'=>12,'name'=>'documentry'],
 ['id'=>10,'name'=>'comedy'],
];

$arr2 = [];
foreach($arr1 as $internal){
  array_push($arr2,$internal['id']);
}

print_r($arr2);

Here we access all internal array's ID's and insert them into a new array.

agentofchaoss
  • 136
  • 1
  • 9