简体   繁体   中英

save output of a foreach ($array as $key => $value) as a readable variable php

I have the following function.

printArray($_POST);
function printArray($array){
     foreach ($array as $key => $value){
        echo "$key: $value <br>";
    } 
}

I modified it from here... Print $_POST variable name along with value

It gets all my html values along with there variable names and echos them. I need to save the output to variable. I've tried using ob..

printArray($_POST);
ob_start();
function printArray($array){
     foreach ($array as $key => $value){
        echo "$key: $value <br>";
    } 
}
$out = ob_get_contents();
ob_end_clean();
print $out;

and that just gives me nothing. Ive tried just saving my echo to a variable and that gets me closer...

function printArray($array){
     foreach ($array as $key => $value){
        echo "$key: $value <br>";
    } 
}

but it only gives me the last value in my output. Help me out here what am i doing wrong.

see...

Postman call and result

<?php
printArray($_POST);
function printArray($array){
    $result = [];
    foreach ($array as $key => $value){
       $result[] = (object)[
            $key => $value
       ];
   } 
   header('Content-Type: application/json; charset=utf-8');
   echo json_encode($result);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM