Reputation: 291
I try to parse xml into arrays. I have got 2 types of incoming data: 1)
<rows>
<item>
<a>A</a>
<b>B</b>
</item>
<item>
<c>C</c>
<d>D</d>
</item>
</rows>
2)
<rows>
<item>
<e>E</e>
<f>F</f>
</item>
</rows>
I create an object of SimpleXMLElement and then convert it in array as in Converting a SimpleXML Object to an Array using first answer. The result in first case is
[ '0' => ['a' => 'A', 'b' => 'B'], '1' => ['c' => 'C', 'd' => 'D']].
The result in second case is ['e' => 'E', 'f' => 'F']
But I need a numeric key in second case [ '0' => ['e' => 'E', 'f' => 'F']]
How to fix it?
Upvotes: 1
Views: 39
Reputation: 163372
For your given example, I think you could use array_values which (from the docs):
returns all the values from the array and indexes the array numerically.
$xml = simplexml_load_string($source);
$result = array_values(json_decode(json_encode($xml), true));
var_dump($result);
Will give you:
array(1) {
[0]=>
array(2) {
["e"]=>
string(1) "E"
["f"]=>
string(1) "F"
}
}
Upvotes: 1
Reputation: 1172
If you have your e,f array (Which is the output of your second case, but i've generated it here. Just use your XML array from your second case)
$arr1 = array(
'e' => 'E',
'f' => 'F',
'g' => 'G',
'h' => 'H',
);
you can then do
$arr2 = array_chunk($arr1, 2);
which will give you the output ($arr2):
[0 => ['e' => 'E', 'f' => 'F'], 1=> ['g' => 'G', 'h' => 'H']]
and that will work assuming that you want your sub arrays to always be 2 items in length. You can change that by changing the second parameter of array_chunk().
Upvotes: 1