0

With fetchAll(PDO::FETCH_ASSOC) get such array

$array = 
Array
(
    [0] => Array
        (
            [FinalCurrencyRate] => 0.000062
        )
)

Need to json_encode to use in

$.post("__02.php", { 'currency': currency }, function(data, success) {
$('#currency_load').html(data.FinalCurrencyRate);
$('#currency_load0').html(data.FinalCurrencyRate0);
$('#currency_load1').html(data.FinalCurrencyRate1);//and so on
}, "json");

If simply echo json_encode($array); then does not work.

Need to convert to json format array like this:

$arr = array ('FinalCurrencyRate'=>"0.000062");

To convert to json format, wrote such code

$json_array = "{";
$flag_comma = 0;
foreach($array as $i =>$array_modified) {

if ($flag_comma == 0) {
$json_array .="'FinalCurrencyRate". $i."'=>'". $array_modified[FinalCurrencyRate]. "'";
$flag_comma = 1;
}
else {
$json_array .=", 'FinalCurrencyRate". $i."'=>'". $array_modified[FinalCurrencyRate]. "'";
}

}
$json_array .= "}";

Then echo json_encode($json_array);. And only one echo json_encode.

But does not work.

Understand that there are errors in code to convert to json format. What need to correct, please?

14
  • 2
    Just a little question back: Do you know what the 404 status code stands for? Commented Aug 25, 2013 at 8:06
  • I see that 404 is Not Found. Commented Aug 25, 2013 at 8:08
  • OK. But the question is about php code convert php array json format array. There is some errors in code and need to understand what to correct. Commented Aug 25, 2013 at 8:09
  • 1
    @user2465936 404 Not Found means that you are trying to access a page that doesn't exist. Most likely you made a typo in your url. json_encode is perfectly able to turn a multidimensional array into a json string. Commented Aug 25, 2013 at 8:11
  • 2
    @user2465936 No, that is not what a 404 error means. A 404 error is invoked by your httpd service. It never executes your page. Commented Aug 25, 2013 at 8:14

1 Answer 1

1

If I understand correctly you just want to return the first row form your array, then you just need to do this

echo json_encode($array[0]);

UPDATE

I think I see what you're trying to do now, you're trying to append the index to the FinalCurrencyRate key in each row. No need to do that, what you should do is change your javascript code to look like this:

$('#currency_load0').html(data[0].FinalCurrencyRate);
$('#currency_load1').html(data[1].FinalCurrencyRate);//and so on
Sign up to request clarification or add additional context in comments.

1 Comment

Want to return whole array. May be to use inside foreach $array[$i]. Thanks for advice. I will try (may be to modify array).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.