2

I am trying to loop though an existing multidimensional array grabbing certain values based on a key.

myarray = [];
for($i = 0; $i < count(exampleArray); $i++){
  $myarray = $exampleArray[$i]['wanted_field'];
}

This is only giving me one value.

The desired output will have a structure similar to this

myarray = ([0]=> 'apple' [1]=> 'orange'
           [0]=> 'plum' [1]=> 'grape' [3]=> 'potato'
          )
1
  • 1
    one thing;- the desired output you shown will not possible because same indexes are over-written with latest values inside array. So i think you need to reformat your desired output a bit Commented Dec 19, 2017 at 16:00

2 Answers 2

5

Problem:- You are over-writing your variable $myarray inside for() loop.

Solution:- You have to do it like below:-

$myarray = []; // you misses $
for($i = 0; $i < count($exampleArray); $i++){ // you forget $ again
  $myarray[] = $exampleArray[$i]['wanted_field']; //assign values to array
}

Or simply you can use array_column():-

$myarray= array_column($exampleArray, 'wanted_field');

Output of both example:- https://eval.in/922152

Sign up to request clarification or add additional context in comments.

Comments

3

If you just want to extract the values of one column from an array...

$myArray = array_column($exampleArray, 'wanted_field');

In your case, you were just overwriting the value to the last value in the array.

2 Comments

I scrolled down to post this as an answer and there it already was.
I also see it's been added to other answers as well.

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.