How to add keys and values to an array? [closed]

北城以北 提交于 2019-12-13 06:02:15

问题


I am using following code to parse the following xml and add the id of each person as key of the array and their names as the values of the array.

The code properly works but the array is not.

   $array = array();
   $category = $xml->xpath('descendant::person');
    foreach ($person as $p) {
    $array[$p['id']] = $p['name'];
    }
 <?xml version="1.0" encoding="utf-8"?>
 <people>
   <person name="Joe" id="134">
   <person name="Jack" id="267">
   </person>
   </person>

   <person name="Ray" id="388">
   <person name="John" id="485">
   <person name="Rayan" id="900">
   </person>
   </person>

   <person name="Alex" id="590">
   </person>
 </people>

The XML is not valid but I ca not make it valid. However the code is working and I just need to assign the ids and values to the array.


回答1:


Lots of little issues going on here ... the biggest problem, though, is that you can't use a simplexml object node as an index in an array. It has to be manually cast as a string or integer. You'd also be better served tweaking your xpath expression a bit, and your loop shouldn't be on $person, which is a variable that doesn't exist, but instead on $category. Try this as an alternative:

$array = array();
$category = $xml->xpath('//person');
while(list( , $p) = each($category)) {
        $array[(string)$p['id']] = (string)$p['name'];
}
print_r($array);

Also note that, if your XML is not valid XML, then it does matter ... simplexml libraries will never function properly on invalid XML (the XML in your example has some improper nesting).




回答2:


I don't know this is the correct method, But I have tested this one and its working fine,

$xml = simplexml_load_string($response);
 $category = $xml->xpath('descendant::person');

 $array = array();

  foreach($category as $each){
    $name_obj = $each->attributes()->name[0];

     $name_json = json_encode($name_obj);
    $name_array = json_decode($name_json, TRUE);


    $id_obj = $each->attributes()->id[0];

  $id_json = json_encode($id_obj);
  $id_array = json_decode($id_json, TRUE);

  $array[$id_array[0]] = $name_array[0];
}

 print_r($array);



回答3:


Are you sure the XML should not be like this?:

<?xml version="1.0" encoding="utf-8"?>
<people>
    <person name="Joe" id="1"></person>
    <person name="Jack" id="2"></person>
    <person name="Ray" id="3"></person>
    <person name="John" id="4"></person>
    <person name="Alex" id="5"></person>
</people>


来源:https://stackoverflow.com/questions/14065060/how-to-add-keys-and-values-to-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!