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'
)
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments