Implementation of foreach

1
<?php

$busca = $_GET['genero'];

$xml_string = file_get_contents("livros.xml");
$xml_object = simplexml_load_string($xml_string);

for ($i=0; $i < count($xml_object->livro); $i++) { 

    for ($j=0; $j < count($xml_object->livro[$i]->genero->descricao); $j++) { 

        if($busca == $xml_object->livro[$i]->genero->descricao[$j]){

            echo $xml_object->livro[$i]->titulo."<br>";
            echo $xml_object->livro[$i]->genero->descricao."<br>";
            echo $xml_object->livro[$i]->isbn."<br>";
            echo $xml_object->livro[$i]->autor."<br>";
            echo $xml_object->livro[$i]->publicacao."<br>";
            echo fLocalMostraGenero($xml_object->livro[$i])."<br>";
        }
    }

    $xml_object->livro[$i]->titulo;

}

function fLocalMostraGenero($livro){

    for($i = 0; $i < count($livro->genero->descricao); $i++)

    {
        echo $livro->genero->descricao[$i];
    }
}

I made this code to perform a gender search inside an xml. A colleague told me to use the foreach instead of mine for normal, but I did not quite understand how it works and how to do this exchange in my code. Can anyone give me an explanation?

    
asked by anonymous 07.03.2018 / 18:28

2 answers

0

Dude, the foreach in php has the second syntax:

foreach (array_expression as $key => $value)
    statement

For example:

$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}

When you use a foreach, it loops through all elements of the array one by one. In the example code, with each pass of the loop, $value is one of the array elements. In this case, you would multiply by two all elements of the array $arr

    
07.03.2018 / 18:38
0

In php, foreach works as follows

foreach(array as [key] => value){

}

Where: array = > the array you want to go through key = > position in the array you are value = > the value inside the array.

For example, we have an array with the following data

$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

To get this data, we'll do

foreach($array as $key => $value){
      //se dermos um echo no $value, temos a seguinte forma
      echo $value->foo

}

In the above example will present the value "bar", remembering that to access in php we use "- >"

For more information use the Next link

    
07.03.2018 / 18:39