skip to Main Content

I got 2 objects with 2 different evaluate():

$bulltin_name = $xpath->evaluate('//body/div/div/div/ul/li/a'); 
$bulltin_url = $xpath->evaluate('//body/div/div/div/ul/li/a/@href');

I try to extract 3 information from the objects above, $bulletins_number and $purified_bulletin_name from $bulltin_name:

foreach($bulltin_name as $element)
{
    $purified_bulletin_name = "";
    $bulletin_name = $element->textContent;
            
    for ($a = 0; $a < strlen($bulletin_name); $a++)
    {
        if (substr($bulletin_name, $a, 1) != " ")
        {
            $purified_bulletin_name .= substr($bulletin_name, $a, 1);
        }
    }
    $bulletin_number = strval(mb_substr($purified_bulletin_name, 4, 3, 'UTF-8'));

    print_r($bulletin_number .": " . $purified_bulletin_name . "<br>");
}

and also $bulltins_url from $bulltin_url:

 foreach($bulltin_url as $url)
 {
      $bulltins_url = $url->textContent;
      print_r("https://www.info.gov.hk" .$bulltins_url. "<br>"); 
 }

They work perfectly, if they are separate. But I want to combine these 2 foreach loop together within one loop only so that it will be easier for further operation. But how should I do that. I searached in the internet and it seems that it is not possible to use 2 loops and elements within one foreach loop.

I want to perform an operation like this:

{
    // A loop (for loop? or some other loop?)
    // some operations here
    // some operations here
    // some operations here

    print_r($bulletin_number .": " . $purified_bulletin_name . ", ". $bulltins_url . "<br>");
}

But how should I do this?

2

Answers


  1. $numbers = array(1, 2, 3, 4, 5);
    foreach ($numbers as $number) {
        echo $number . " ";
    }
    // Output: 1 2 3 4 5
    
    $person = array("name" => "John", "age" => 30, "city" => "New York");
    foreach ($person as $key => $value) {
        echo $key . ": " . $value ;
    }
    
    Login or Signup to reply.
  2. Since the second expression is used to obtain the href attributes of the first one, you can also obtain them with the getAttribute method:

    foreach($bulltin_name as $element)
    {
        .....
        $bulletin_name = $element->textContent;
        $bulltins_url = $element->getAttribute('href');
        .....
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search