This is because you’re not adding elements to the array. You’re overwriting them:
$modified_result = array();
foreach($queryresult as $result){
$modified_result['name'] = $result->name;
$modified_result['address'] = $result->address;
}
Your loop is setting the name
and address
property of the $modified_result
array directly, and then replacing them for each item in the loop.
You want $modified_result
to be an array of arrays, which means that for each $result
you need to add a new array to $modified_result
. You can do this with $modified_result[]
:
$modified_result = array();
foreach ( $queryresult as $result ) {
$modified_result[] = array(
'name' => $result->name,
'address' => $result->address,
);
}
That being said, I can’t see any reason from you code why you can’t just query the fields you want to begin with. Then you don’t need the loop at all:
$queryresult = $wpdb->get_results( "SELECT name, address FROM ..." );
$datadump = json_encode( $queryresult );
echo file_put_contents( 'my_output.json', $datadump );