2

I have an array like this $items():

Array
    (
    [0] => Array
    (
        [id] => 1
        [first_name] => fname1
        [laste_name] => lname1
        [Age] => 20
     )
    [1] => Array
   (
        [id] => 2
        [first_name] => fname2
        [laste_name] => lname2
        [Age] => 22
    )
  )

And I want to create another array only with [id] and [Age]

Array
    (
    [0] => Array
    (
        [id] => 1
        [Age] => 20
     )
    [1] => Array
   (
        [id] => 2
        [Age] => 22
    )
  )

So I have tried looping like this :

$array = array();
foreach($items as $item) {
     $array['id']= $item['id'];
     $array['age']= $item['age'];

 }

But It gives only values of the last item

1
  • just little modification needed in your code.. Commented Apr 22, 2015 at 7:39

3 Answers 3

2

Try with -

$array = array();
foreach($items as $item) {
   $temp['id']= $item['id'];
   $temp['age']= $item['age'];
   $array[] = $temp;
}
Sign up to request clarification or add additional context in comments.

Comments

2

Try with .It'll work for you.

$array = array();
foreach($items as $key => $item) {
     $array[$key]['id']= $item['id'];
     $array[$key]['age']= $item['age'];

 }

Comments

1

use this

$array = array();

$new_array = array();

foreach($items as $item) {
     $array['id']= $item['id'];
     $array['age']= $item['age'];
     $new_array[] = $array;
 }

print_r($new_array);

Your result is :

  Array
    (
    [0] => Array
    (
        [id] => 1
        [Age] => 20
     )
    [1] => Array
   (
        [id] => 2
        [Age] => 22
    )
  )

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.