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.

Link to comment
Share on other sites

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++;
}

}

Link to comment
Share on other sites

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 );
        }
    }
}

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.