0

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
cinameng
  • 313
  • 4
  • 14

1 Answers1

1
$array = array();
foreach($data as $f){
 $array['field1']=$f->value;
}
  • 1
    can you explain. Code only answers are rarely informative or helpful – Martin Jul 10 '17 at 12:00
  • Yes sure, As per above requirement he want array key is same and value will be changed. So First I can define an array after that I am start foreach loop. In foreach loop I a can define default key and all store value in this array. If I am wrong so please tell me. – Avinash Kumar Singh Jul 10 '17 at 12:05
  • 1
    So... please **edit** your answer and add the details to the answer, rather than in an easily missable comment – Martin Jul 10 '17 at 15:12