Foreach implementation

Asked

Viewed 114 times

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 within an xml. A colleague told me to use the foreach instead of my for normal, but I did not understand very well how it works and how to make this change in my code. Can someone give me an explanation?

  • Take a look at this Soen question: https://stackoverflow.com/questions/4637617/how-to-use-foreach-with-php-xml-simplexml

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, every step of the loop, $value is one of the array elements. In this case, multiply by two all array elements $arr

0

In php, foreach works like this

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

}

Where: array => the array you want to go through key => position in the array you are traversing value => the value you have 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 example above you will present the value "bar", remembering that to access in php we use the "->"

For more information use the Following link

Browser other questions tagged

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