首页 > 解决方案 > php foreach 返回数组丢失

问题描述

我有一个必须用以前的数组值编译的字符串:

$arry="<root>
<president><title>apple</title></president>
<president><title>orange</title></president>
<president><title></title></president>
<president><title></title></president>
<president><title>lime</title></president>
<president><title>blu</title></president>
</root>";



$arr=explode('<president>',$arry);
$count=0;
    foreach($arr as $str){  
        if($count!=0){
            $title=explode('<title>',$str); 
            $title=explode('</',$title[1]);
            $title=$title[0];
            echo $title."<br>";
        }
    $count++;

    }

输出是:

//apple
//orange
//
//
//lime
//blu

我需要用前一个值完成缺少的标题。

我希望结果是:

//apple
//orange
//orange
//orange
//lime
//blu

标签: php

解决方案


它的 XML,您可以使用simplexml_load_string() / simplexml_load_file()将其直接解析为可用对象,然后您可以循环检查值是否为空,否则使用先前的:

<?php
$xml = simplexml_load_string('<root>
<president><title>apple</title></president>
<president><title>orange</title></president>
<president><title></title></president>
<president><title></title></president>
<president><title>lime</title></president>
<president><title>blu</title></president>
</root>');

// print_r((string) $xml->president[0]->title); // apple

所以循环它并应用回顾

foreach ($xml->president as $president) {
    if (!empty($president->title)) {
        $last = $president->title;
    } else {
        $president->title = $last ?? null;
    }
    echo $president->title.PHP_EOL;
}

https://3v4l.org/k2Ghq

结果:

apple
orange
orange
orange
lime
blu

并转换回 XML 字符串以与file_put_contents()等一起存储,请使用asXML()

$xml->president[3]->title = 'foo';
echo $xml->asXML();

https://3v4l.org/KEZ2Y

<?xml version="1.0"?>
<root>
<president><title>apple</title></president>
<president><title>orange</title></president>
<president><title/></president>
<president><title>foo</title></president>
<president><title>lime</title></president>
<president><title>blu</title></president>
</root>

推荐阅读