Looking for some input on this one. I am writing a custom array but having a strange issue. It seems to be cycling through the loop and dropping previous values and only storing the last row of the query. Any ideas?
global $wpdb;
$queryresult = $wpdb->get_results(select query);
$modified_result = array();
foreach($queryresult as $result){
$modified_result['name'] = $result->name;
$modified_result['address'] = $result->address;
}
$datadump = json_encode($modified_result);
echo file_put_contents('my_output.json', $datadump);
// outputs {"name":"Mark","address":"1313 Mockingbird Lane"}
// which is only the LAST row in the query instead of
// building an array of ALL names and addresses that should be
// produced by the loop. Any ideas anyone?
Looking for some input on this one. I am writing a custom array but having a strange issue. It seems to be cycling through the loop and dropping previous values and only storing the last row of the query. Any ideas?
global $wpdb;
$queryresult = $wpdb->get_results(select query);
$modified_result = array();
foreach($queryresult as $result){
$modified_result['name'] = $result->name;
$modified_result['address'] = $result->address;
}
$datadump = json_encode($modified_result);
echo file_put_contents('my_output.json', $datadump);
// outputs {"name":"Mark","address":"1313 Mockingbird Lane"}
// which is only the LAST row in the query instead of
// building an array of ALL names and addresses that should be
// produced by the loop. Any ideas anyone?
Share
Improve this question
asked Jan 14, 2020 at 1:41
simlpymarkbsimlpymarkb
1033 bronze badges
1 Answer
Reset to default 2This 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 );
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744839051a4596444.html
评论列表(0条)