cinameng
cinameng

Reputation: 323

Get a column from a 2d array

I'm trying to print the contents of a table so that only the 4 latest entries are displayed.

$query = "SELECT `field1`, `field2` ,`field3`,`field4`  FROM myTable 
ORDER BY date DESC LIMIT 4 ";

$result = mysqli_query($connection, $query);

while ($row = mysqli_fetch_assoc($result)) {print_r($row);}

this returns the following for each requested entry (x4):

Array
(
[field1] => value
[field2] => value
[field3] => value
[field4] => value
)

what I want is to create an array that looks like this:

Array
(
[field1] => value1
[field1] => value2
[field1] => value3
[field1] => value4
)

I've tried this which looks to be correct but is not doing what I want, instead it's creating a new array for each entry:

$a = array($row);
$field1 = array_column($a, 'field1');
print_r($field1);

Any help is appreciated as I'm new to php.

Upvotes: 0

Views: 57

Answers (1)

Avinash Kumar Singh
Avinash Kumar Singh

Reputation: 117

$array = array();
foreach($data as $f){
 $array['field1']=$f->value;
}

Upvotes: 1

Related Questions