2 votes

Comment boucler dans un tableau multidimensionnel et comparer les valeurs ?

J'utilise le script PHP présenté ci-dessous qui prend les données XML de l'API Flickr et donne un tableau, mais je ne sais pas comment récupérer les valeurs de ce tableau et faire quelques opérations avec.

Le tableau a ce format :

XmlElement Object
(
    [name] => rsp
    [attributes] => Array
        (
            [stat] => ok
        )

    [content] => 
    [children] => Array
        (
            [0] => XmlElement Object
                (
                    [name] => photos
                    [attributes] => Array
                        (
                            [page] => 1
                            [pages] => 13751
                            [perpage] => 100
                            [total] => 1375086
                        )

                    [content] => 
                    [children] => Array
                        (
                            [0] => XmlElement Object
                                (
                                    [name] => photo
                                    [attributes] => Array
                                        (
                                            [id] => 25000430521
                                            [owner] => 73422502@N08
                                            [secret] => 19459b26e4
                                            [server] => 1703
                                            [farm] => 2
                                            [title] => Health
                                            [ispublic] => 1
                                            [isfriend] => 0
                                            [isfamily] => 0
                                            [url_m] => https://farm2.staticflickr.com/1703/25000430521_19459b26e4.jpg
                                            [height_m] => 500
                                            [width_m] => 500
                                        )

                                    [content] => 
                                    [children] => 
                                )

                            [1] => XmlElement Object
                                (
                                    [name] => photo
                                    [attributes] => Array
                                        (
                                            [id] => 35305743196
                                            [owner] => 73422502@N08
                                            [secret] => 9601255217
                                            [server] => 4232
                                            [farm] => 5
                                            [title] => Health
                                            [ispublic] => 1
                                            [isfriend] => 0
                                            [isfamily] => 0
                                            [url_m] => https://farm5.staticflickr.com/4232/35305743196_9601255217.jpg
                                            [height_m] => 333
                                            [width_m] => 500
                                        )

                                    [content] => 
                                    [children] => 
                                )

Voici ce que j'essaie d'accomplir :

J'essaie d'utiliser ces 2 valeurs
'[height_m] => 333 [width_m] => 500'.

et utiliser la construction if..

 if (**width_m** / **height_m** >= 1.25 ) { 
 echo "<img src=" **url_m** " width="100">;
 }
 else {
 echo "<img src=" **url_m** " width="50">;
 }

Comment puis-je obtenir cette construction dans une boucle for each ?

Le code qui génère le tableau provient d'un utilisateur génial à l'adresse suivante php.net

class XmlElement {
  var $name;
  var $attributes;
  var $content;
  var $children;
};

function xml_to_object($xml) {
  $parser = xml_parser_create();
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, $xml, $tags);
  xml_parser_free($parser);

  $elements = array();  // the currently filling [child] XmlElement array
  $stack = array();
  foreach ($tags as $tag) {
    $index = count($elements);
    if ($tag['type'] == "complete" || $tag['type'] == "open") {
      $elements[$index] = new XmlElement;
      $elements[$index]->name = $tag['tag'];
      $elements[$index]->attributes = $tag['attributes'];
      $elements[$index]->content = $tag['value'];
      if ($tag['type'] == "open") {  // push
        $elements[$index]->children = array();
        $stack[count($stack)] = &$elements;
        $elements = &$elements[$index]->children;
      }
    }
    if ($tag['type'] == "close") {  // pop
      $elements = &$stack[count($stack) - 1];
      unset($stack[count($stack) - 1]);
    }
  }
  return $elements[0];  // the single top-level element
}

0voto

FabianGillenius Points 571

L'approche la plus simple que je puisse concevoir (remplacer "$Object" par le nom de la variable de votre objet XMLElement) :

foreach($Object->children[0]->children as $child) {
    if ($child->attributes['width_m'] / $child->attributes['height_m'] >= 1.25 ) { 
        echo "<img src=" . $child->attributes['url_m'] . " width="100">;
    }
    else {
        echo "<img src=" . $child->attributes['url_m'] . " width="50">;
    }
}

0voto

Miroslav Glamuzina Points 3400

Ce n'est pas une boucle foreach mais cela fait essentiellement la même chose :

$allImageHtml = array_map(function($photoData){
    $width = ($photoData->attributes['width_m'] / $photoData->attributes['height_m']) >= 1.25 ?100:50;
    return "<img src='{$child->attributes['url_m']} width='{$width}'/>";
}, $Object->children[0]->children);

echo implode('<!-- Separator HTML. (ie: br) -->', $allImageHtml);

Si vous préférez une foreach boucle :

foreach($Object->children[0]->children as $photoData){
    $width = ($photoData->attributes['width_m'] / $photoData->attributes['height_m']) >= 1.25 ? 100: 50;
    $spacer = "<!-- Separator HTML. (ie: br) -->";
    echo "<img src='{$child->attributes['url_m']} width='{$width}'/>{$spacer}";
}

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X