How to format an array php

1

I am doing a SQL query in my model and controller , I am printing the array values.

The view looks like this:

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

But I would like to format it like this:

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

How to do it?

This is my foreach :

foreach ($variavel1 as $key) {
   print_r($key);
}
    
asked by anonymous 10.09.2018 / 22:21

3 answers

-1

Let's see that you are printing a subarray that is found by for each if you want to print this way you are no longer having an array and have a string you can do this by the 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'
    
10.09.2018 / 22:42
2

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

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 pre tag is intended to make it easier to read the data, preserving the spaces and line breaks returned by print_r .

And the function print_r when it has the second parameter informed as true instead of printing, returns the information so we can use as we wish.

    
11.09.2018 / 00:59
0

Try user Yii2's own VarDumper

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

It's a bit different from the way it's illustrated, but that way it's very clear

    
21.11.2018 / 20:06