0

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?
2

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 );
  • Worked like a charm. Thanks for your help. The reason why I didn't query the fields directly is because I am running a custom function against one of the columns that modifies the value and sends it to a custom array for another use in my plugin across several lookup functions. -Cheers! – simlpymarkb Jan 14 at 2:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.