php - 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
解决方案
它的 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;
}
结果:
apple
orange
orange
orange
lime
blu
并转换回 XML 字符串以与file_put_contents()等一起存储,请使用asXML()
$xml->president[3]->title = 'foo';
echo $xml->asXML();
<?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>
推荐阅读
- python - 获取合并两个数据集的数据集格式
- python - 不确定这里出了什么问题,无论我尝试什么,它都会返回 TypeError: 'NoneType' object is not iterable
- oracle - 数字的 Oracle 字节大小
- r - 在 R Lubridate 中解析我的日期时间时出现问题
- php - 如何使用 cakephp 2 在视图中显示树视图
- selenium - 复选框中的 Xpath 定位器
- vue.js - 无法对 Vuesax 数据表中的日期列进行排序
- c++ - 关于抽象类(cpp)的运算符重载
- unity3d - 统一地牢生成
- c++ - 使用 Sony Camera Remote SDK 获取照片