开发者

Problem in getting multidimensional array from simple xml object

开发者 https://www.devze.com 2023-01-01 15:07 出处:网络
As a newbie I need your help in getting multidimensional array from simplexml object. suppose my array is like:

As a newbie I need your help in getting multidimensional array from simplexml object. suppose my array is like: just for getting idea:

Here $data is a simplexml object contains below xml:

<users>
  <user>
    <id></id>
    <nm></nm>
    <gender>
      <male></male>
      <female></female>
    </gender>
  </user>
</users>

Here I an perfectly getting array of each user, but in that array when it comes to gender, it shows nothing. i need array of gender too. I am using following code:

foreach($data->users as $users)开发者_如何学Python
{
  $arr1 = array();
  foreach($users as $user)
  {
    foreach($user as $k=>$v)
    {
      $arr1[$k] = (string) $v;
    }
  }
  $arr2[] = $arr1;
}

Any suggestion?


You're not using the foreach iterator correctly. It should be something like this:

$users = simplexml_load_string($the_xml_thing_you_posted);

foreach ($users->user as $user)
{
    $arr[] = array(
        'id' => (string) $user->id,
        'nm' => (string) $user->nm
    );
}

Now I have no idea what you're trying to do with your gender thing, both elements are empty, what does that mean?


foreach($user as $k=>$v) doesn't iterate over all the child elements in your user element. It iterates over all user elements that are children of $users. For illustration:

$data = new SimpleXMLElement('<data>
  <users id="1">
    <user id="user1a"></user>
    <user id="user1b"></user>
  </users>
  <users id="2">
    <user id="user2a"></user>
    <user id="user2b"></user>
  </users>
</data>');

foreach($data->users as $users)
{
  echo 'users id: ', $users['id'], "\n";
  foreach($users as $user)
  {
    echo "  user id: ", $user['id'], "\n";
  }
}

prints

users id: 1
  user id: user1a
  user id: user1b
users id: 2
  user id: user2a
  user id: user2b

You probably want something more like

$data = new SimpleXMLElement('<data>
  <users>
    <user>
      <propA>A1</propA>
      <propB>B1</propB>
      <propC>C1</propC>
    </user>
    <user>
      <propA>A2</propA>
      <propB>B2</propB>
      <propC>C2</propC>
    </user>
  </users>
</data>');

$result = array();
foreach($data->users as $users)
{
  foreach($users as $user)
  {
    $arr = array();
    foreach($user->children() as $e) {
      $arr[$e->getName()] = (string)$e;
    }
    $result[] = $arr;
  }
}

print_r($result);

which prints

Array
(
    [0] => Array
        (
            [propA] => A1
            [propB] => B1
            [propC] => C1
        )

    [1] => Array
        (
            [propA] => A2
            [propB] => B2
            [propC] => C2
        )

)
0

精彩评论

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

关注公众号