Jump to content

Looping through an array for foreach and breaking up strings with explode


gholland85

Recommended Posts

Hello, I've converted an XML file to an array and I need to be able to loop through it and split up the 'name' field to separate the first and last name. I've worked out how to separate a single name in the array but can't work out how to loop through them all with foreach. Would anyone be able to help me out with this? Here is the code I have so far to explode the name for the first item in the array (0)

 

include("xml2array.php");
$xml=xml2ary(file_get_contents('http://www.mypage.local/config/reviews.xml'));
$xml = $xml[reviews][_c][Detail];

//splits first name and last name
$xml[0][_a]["textbox5"] = explode(" ", $xml[0][_a]["textbox5"]);
echo $xml[0][_a]["textbox5"][1] ;

 

Any help much appreciated.

Cheers,

Greg.

Ok, so I half worked it out. The code below seems to work however every 2nd row in the array in blank. Any ideas where I'm going wrong here?

 

Thank you.

 

foreach($xml as $v1) {
foreach($v1 as $v2) {  
	$exploded = explode(" ", $v2[textbox5]);
	$days = round(strtotime($v2["textbox13"]) - strtotime($v2["textbox10"])) / (60 * 60 * 24);
	$reviewname[$i] = array("first_name" => $exploded[0], "last_name" => $exploded[1], "nights_stayed" => $days );
	$i++;
}

}

Can't really say without seeing the input data, but I would guess that some "records" do not have the 'textbox5' key (you know you should enclose the string key name in quotes, right?). Also, you don't need to use $i, just use [].

 

Try this:

foreach($xml as $v1)
{
    foreach($v1 as $v2)
    {
        if(isset($v2['textbox5']))
        {
            $name = explode(" ", $v2['textbox5']);
            $days = round(strtotime($v2['textbox13']) - strtotime($v2['textbox10'])) / (60 * 60 * 24);
            $reviewname[] = array("first_name" => $name[0], "last_name" => $name[1], "nights_stayed" => $days );
        }
    }
}

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.