0

I want to know that is there a way to insert certain elements of an array into a new array. I mean I have an array containing 10 objects. Each object has 3 or four fields for example id, name , age , username. now I want to insert the id's of all the objects into the new array with a single call.Is there anyway to do that.

$array = [ 
  [0] => [
      id   =>      
      name =>
  ],
  [1] = > [
      id   =>
      name =>
  ]
]

and so on now I want to insert all the id's of all the object into a new array with a single call. Is there a way to do that?

1
  • 1
    Why does it have to be a "single call"? That's a strange requirement Commented Jan 19, 2016 at 13:26

4 Answers 4

1

Use array_map() function.

Here is your solution:-

 $ids = array_map( function( $arr ){
                    return $arr["id"];
                }, $arr );

 echo '<pre>'; print_r($ids);
Sign up to request clarification or add additional context in comments.

6 Comments

can you tell me just one more thing that if I have multiple arrays, can I give all the arrays after the call back ??
If all arrays have same structure then first merge them. Is array_map working for you?
I have not used it but I think it will do what I want. Let me check
I know I can merge them but just for knowledge can I give it multiple arrays having same structure ?
No you can not pass multiple array within same function for same operation.
|
0

A basic foreach loop will do the job just fine

$firstArray = array(
  array(
    'id' => 1,
    'name' => 'abc'
  ),
  array(
    'id' => 2,
    'name' => 'def'
  ),
  array(
    'id' => 3,
    'name' => 'gh'
  )
);

$onlyIds = array();
$onlyKeys = array();

//To get the array value 'id'
foreach($firstArray as $value){
  $onlyIds[] = $value['id'];
}

//To get the array keys
foreach($firstArray as $key => $value){
  $onlyKeys[] = $key;
}

1 Comment

I know a simple for loop will be fine but it's a requirement that I do it with a single call
0

You could use array_walk which could be considered a "single call"

$array = array(0 => array('id', 'name', 'age'), 1 => array('id', 'name', 'age'));
array_walk($array, function($item, $key) {
    // $key is 0 or 1
    // $item is either id, name, age
});

Comments

0

You can use array_column.

$arr = [ ['id' => 1, 'username' => 'a'], ['id' => 2, 'username' => 'b'] ];
$ids = array_column($arr, 'id')
$ids == [1, 2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.