Forum Moderators: coopster

Message Too Old, No Replies

displaying non array/arrays

         

Expo

12:24 am on Dec 15, 2009 (gmt 0)

10+ Year Member



I'm using xml2array to convert an XML file to an array (obviously...)

I'm listing these items in a form and when I get to an array I do foreach.

My problem is that sometimes foreach doesn't work when there is one item...

here's the one item array


[parts] => Array
(
[qty] => 1
[partno] => #DST50297618006
[price] => 48.86

)

Here's one that works


[parts] => Array
(

[qty] => Array
(
[0] => 1
[1] => 0
)

[partno] => Array
(
[0] => #NEWPRO
[1] => #CDA FW420
)

[price] => Array
(
[0] => 349.00
[1] => 0.00
)


)

I was going to use is_array and then do two sets of code but I'm wondering if there is a better way?

ALKateb

11:09 am on Dec 15, 2009 (gmt 0)

10+ Year Member



this is not a matter of 1 item in the array or more it is a matter of 1D array or 2D
as u can notice when there is more than one item the code is splitting the qty in an array,partno in array and price in another array

if you want to test whether it is 1D array or 2D array you do not want to use is_array cos they both are arrays anyway unless you mean to do (is_array($array[0]) then yes it would do it

but you can perform this test:
let's assume your array is $array
if(!is_array($array[0])){
$newarray[0] = $array;
}

now you can deal with $newarray the way you are doing now cos it is 2D

ALKateb

11:29 am on Dec 15, 2009 (gmt 0)

10+ Year Member



but if you want to convert it to make it the same format as the xml2array to avoid using two bits of codes you can convert it this way

foreach ($array as $key =>$value){
$newarray[$key] = array($value);
}

Expo

12:10 pm on Dec 15, 2009 (gmt 0)

10+ Year Member



Thanks! that's exactly what I wanted to do - avoid duplicate code.