I am pretty new to PHP and hope someone here can help me with the following.

我是PHP的新手,希望有人可以帮我解决以下问题。

I have a simpleXML object that looks as follows (shortened):

我有一个simpleXML对象,如下所示(缩写):

<ranks>
  <history>
    <ranking>1</ranking>
    <groupName>currentMonth<item>item1</item><groupCount>53</groupCount></groupName>
  </history>
  <history>
    <ranking>2</ranking>
    <groupName>currentMonth<item>item2</item><groupCount>20</groupCount></groupName>
  </history>
  <history>
    <ranking>3</ranking>
    <groupName>currentMonth<item>item3</item><groupCount>7</groupCount></groupName>
  </history>
  <history>
    <ranking>4</ranking>
    <groupName>currentMonth<item>item4</item><groupCount>4</groupCount></groupName>
  </history>
  <history>
    <ranking>5</ranking>
    <groupName>currentMonth<item>item5</item><groupCount>2</groupCount></groupName>
  </history>
  <history>
    <ranking>6</ranking>
    <groupName>currentMonth<item>item6</item><groupCount>2</groupCount></groupName>
  </history>
  <history>
    <ranking>7</ranking>
    <groupName>currentMonth<item>item7</item><groupCount>1</groupCount></groupName>
  </history>
</ranks>

How can I convert this into an array using PHP that has the following structure (hard-coded for demoing)?

如何使用具有以下结构的PHP将其转换为数组(硬编码用于演示)?

$arr = array("item1"=>"53","item2"=>"20","item3"=>"7","item4"=>"4","item5"=>"2","item6"=>"2","item7"=>"1");

Many thanks for any help with this, Mike.

非常感谢Mike的任何帮助。

1 个解决方案

#1


1

It can be done by iterating over the history elements like so:

它可以通过遍历历史元素来完成,如下所示:

$obj = simplexml_load_string($xml); // change to simplexml_load_file if needed

$arr = array();

foreach($obj->history as $history){
    $arr[(string)$history->groupName->item] = (int)$history->groupName->groupCount;
}

Outputs

输出

Array
(
    [item1] => 53
    [item2] => 20
    [item3] => 7
    [item4] => 4
    [item5] => 2
    [item6] => 2
    [item7] => 1
)

更多相关文章

  1. PHP根据数组的值分组
  2. 找出数组中大于或等于N的数
  3. PHP用空格分割文本为数组的方法
  4. 如何使用ChromePhp Logger记录数组
  5. 在数组中计数,其中值为0
  6. 如何获取关联数组的当前元素数?
  7. 如何将PHP数组的关联数组转移到javascript?
  8. PHP - 将字符串转换为键值数组
  9. 如何在不更改其键值的情况下删除数组的第一个元素?

随机推荐

  1. jQuery返回一个没有逗号的字符串的前5个
  2. 超好用的一个JQUERY分页器
  3. Jssor滑块不适用于AngularJS
  4. 如何使用javascript/jquery获取文本框数
  5. ajax防止重复提交
  6. JQuery实现的 checkbox 全选、反选。
  7. 执行Django数据库值的计算:视图。py或Jav
  8. 通过AJAX加载内容和预加载图像?
  9. 使用JQuery从外部文件中通过id选择器获取
  10. 使用jQuery更新textarea值更改的文本