How to format a php array

Asked

Viewed 1,130 times

1

I’m doing an SQL query in my model and in the controller, I’m printing the values of array.

The exhibition is like this:

Array ( [campo1] => 98 [campo2] => SOLO [soma] => 1 ) Array ( [campo1] => 92 [campo2] => DARTH [soma] => 11 ).

But I would like to format like this:

[campo1] => 98 =>[campo2] => 
            SOLO [soma] => 1
[campo2] => 92 =>[campo2] => 
            DARTH [soma] => 11

How to do?

This is my foreach:

foreach ($variavel1 as $key) {
   print_r($key);
}
  • Friend, put the whole method in question of your controller for better analysis

3 answers

2

If you want to see the contents of the array it is not necessary to run a foreach, just use the tag pre HTML together with the function print_r of PHP in this way:

echo '<pre>'.print_r($array, true).'</pre>';

The result will be:

Array
(
    [0] => Array
    (
        [campo1] => 98
        [campo2] => SOLO
        [soma] => 1
    )
    [1] => Array
    (
        [campo1] => 92
        [campo2] => DARTH
        [soma] => 11
    )

)

The tag pre has the objective of facilitating the reading of the data, preserving the spaces and line breaks returned by print_r.

And the function print_r when you have the second parameter reported as true instead of printing, returns the information so that we can use it as we wish.

0

Try Yii2’s own Vardumper user

\yii\helpers\VarDumper::dump($array, 10, true);

It’s a little different from the way you illustrated it, but that way it’s pretty clear

-1


Let’s see you are printing a subarray that is found by for each if you want to print this way you will be no longer having an array and will have a string can do this by implode function

foreach ($variavel1 as $key) {
    $output = implode(', ', array_map(
        function ($v, $k) { return sprintf("[%s]=>'%s'", $k, $v); },
        $key,
        array_keys($key)
    ));
    echo $output."\n";
}

this will print something like

[campo1]=>'98', [campo2]=>'SOLO', [soma]=>'1' 
[campo1]=>'92', [campo2]=>'DARTH', [soma]=>'11'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.