Problem when printing PHP array data

1

I have a problem in the following code, I am trying to print the data 'notes' of the array with 'foreach' but when printing with 'echo' it prints the word 'Array' and does not print the data I want.

$persona1 = [
   'nombre' => 'nombre1',
   'notas' => [1,2,3,4]
];

$persona2 = [
   'nombre' => 'nombre2',
   'notas' => [5,6,7,8]
];


$datos=[$persona1, $persona2];



foreach($datos as $personas){

    echo $personas['nombre'] . " " . $personas['notas'] . " , ";
}

// Me imprime este resultado: nombre1 Array , nombre2 Array
// Como quiero que lo imprima : nombre1 1,2,3,4 , nombre2 5,6,7,8
    
asked by InThaHouse 30.11.2018 в 12:38
source

3 answers

2

The problem you're having because you're trying to print $personas['$notas'] on screen and it's a array .

To be able to access the different notes of the "person" you have to mount another foreach within your foreach to go through said array .

PHP

foreach($datos as $personas){
    echo ($personas['nombre']);
    foreach($personas['notas'] as $nota){
        echo (' '. $nota . ' ');    
    }   
}
    
answered by 30.11.2018 / 12:49
source
3

Print array because what is in notas is an array. The elements of an array can not be printed with echo , you must go through them using a loop: for, while , etc, or use some help function appropriate to what you need.

Since you want to show the notes separated by commas, you can use implode . This function is used to show the elements of an array separated by the character or characters that you indicate in its first parameter.

For example, doing implode(",",$personas['notas']) will show you something like this: 1,2,3,4 . That is, it will extract each value from the array and separate it by , , since you put a comma as the first parameter in the function.

You can therefore write your code like this:

foreach($datos as $personas){
    echo $personas['nombre'] . " " . implode(",",$personas['notas']).PHP_EOL;
}

PHP_EOL is equivalent to the line break, so that it separates each element of the array with a space.

    
answered by 30.11.2018 в 12:52
1

Array is printed because it is actually an array and to print its elements this must be traversed or use some function for arrays that facilitates the work. Ex:

echo implode( “,”, $personas[“notas”] );

The implode function joins the elements of an array in a string concatenated with the character you indicate.

    
answered by 30.11.2018 в 12:53