开发者

php parse xml make result shuffle

test.xml

<?xml version="1.0" encoding="UTF-8"?>
<items>
<item>
  <id>1</id>
  <num>10</num>
  <text>text1</text>
</ite开发者_如何学运维m>
<item>
  <id>2</id>
  <num>8</num>
  <text>text2</text>
</item>
<item>
  <id>3</id>
  <num>17</num>
  <text>text3</text>
</item>
<item>
  <id>4</id>
  <num>5</num>
  <text>text4</text>
</item>
<item>
  <id>5</id>
  <num>9</num>
  <text>text5</text>
</item>
</items>

How to do if <num> >=9 , shuffle the items and print the <text>?

$xml = simplexml_load_file('test.xml');
foreach ($xml->item as $key=>$data){
    if(($data->num)>=9){
        ... 
    }
}

need out put like:

text1 text3 text5 OR text1 text5 text3 OR text3 text1 text5 ... //text1 text3 text5 is not smaller than 9, then print them and make their position radom


When they pass, add them to an (associative) array.

After the foreach loop, shuffle($array) will shuffle them and then print them as usual (echo $array[0].$array[1].$array[2]).

Is this what you were looking for?

EDIT:

$passedArray = array();

$xml = simplexml_load_file('test.xml');
foreach ($xml->item as $key=>$data){
    if(($data->num)>=9){
        $passedArray[] = $data->text;
    }
}

shuffle($passedArray);

And then:

foreach ($passedArray as $value) {
    echo $value.' ';
}

This will leave a trailing space. This is better:

$string = '';

foreach ($passedArray as $value) {
    $string += $value.' ';
}

echo substr($string, 0, strlen($string)-1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜