Help in php with arrays

0

Hello friends I am a beginner in php language, I need to do the following: Create an arrangement with movies and its leading actor. In ANOTHER arrangement to put the movies and their release year. Taking data from both arrangements, show each movie with its leading actor and its premiere year. Example:

Rapidos y Furiosos 8 -- actor: Vin disel -- Estreno: 2017
Star Trek: Into Darkness -- actor: Chris pine -- Estreno: 2013
Los vengadores 3 -- actor: Robert Downey Jr. -- Estreno: 2018 

I put it this way but it shows it 9 times. Thanks for your help.

<?php

    $arreglo1 = array('Rapido y Furioso 8'=>'actor: Vin Disel' , 'Star Trek: Into Darkness'=>'actor: Chris Pine' , 
            'Los Vengadores 3'=>'actor: Robert Downey Jr.');

    $arreglo2 = array('Rapido y Furioso 8'=>'Estreno: 2017' , 'Star Trek: Into Darkness'=>'Estreno: 2013' , 
        'Los Vengadores 3'=>'Estreno: 2018');


foreach ($arreglo1 as $pelicula => $actor) {

        foreach ($arreglo2 as $pelicula => $estreno) {
            echo($pelicula." --- ".$actor." --- ".$estreno."<br>");
        }
}
?>
    
asked by Miguel Gómez 11.09.2017 в 20:58
source

2 answers

1

you have a logic error:

You repeat everything 9 times, because what you are doing is going through a for of 3 elements, and for each of those 3 elements, print the values of another array of 3 elements (3 * 3 = 9)

foreach ($arreglo1 as $pelicula => $actor) {

        foreach ($arreglo2 as $pelicula => $estreno) {
            echo($pelicula." --- ".$actor." --- ".$estreno."<br>");
        }
}

Actually what you want to do, since you did not specify what you really want to do, and it seems like a task exercise, is to print the value of the two arrays, using the same indexes .. so as an example let's say we could do something like this:

foreach($arreglo1 as $pelicula => $actor)
{
   echo ($pelicula." --- " .$actor. " --- " .$arreglo2[$pelicula];
}

Where for each movie of the arrangement1, I look for the associative arrangement2, the same one.

    
answered by 11.09.2017 / 21:48
source
1

Another alternative would be to create a multidimensional array. And make the journey in this way.

$arreglos = array( array( 'pelicula' => 'Rapido y Furioso 8', 'actor' => 'Vin Disel', 'estreno' => 2017 ),
               array( 'pelicula' => 'Star Trek: Into Darkness', 'actor' => 'Chris Pine' , 'estreno' =>2013),
               array( 'pelicula' => 'Los Vengadores 3', 'actor'=> 'Robert Downey Jr.', 'estreno' => 2018) 
             ) ;


print_r($arreglos);
echo "<br>"; // salto de lina

for ($i=0; $i < count($arreglos); $i++){

    echo "<br>"; // salto de lina

    echo $arreglos[$i]['pelicula'] .  " --- actor: " . $arreglos[$i]['actor'] .  " --- estreno: " . $arreglos[$i]['estreno'] ;
}
    
answered by 11.09.2017 в 23:35