简体   繁体   中英

PHP OOP confusion for noobie

I have a problem that's born of being a dyed in the wool procedural programmer who's here forced into using some OOP constructs in order to make use of a library I need to use. I am stuck unable to access variables- other than print them out. Let me illustrate:

foreach($html->find('span[class="given-name"]') as $e)
    echo $e->innertext . '<br>';

foreach($html->find('span[class="family-name"]') as $e)
    echo $e->innertext . '<br>';

The above will print out a long list of first names, followed by a long list of surnames. However I want to be able to access them together. For example I want to be able to say something like $myarray["firstname"] = (*whatever is in $e->innertext*) and also $myarray["surnamename"] = (*whatever is in the next $e->innertext*)

When I try the seemingly obvious:

$x = $e->innertext;

it crashes. I assume that's because I am passing a pointer to $x instead of a value, but how on earth do I tell it I want the value - in this case a part of a person's name, to be assigned to $x , or my array, or whatever the variable might be?

I am almost a complete neophyte when it comes to OOP concepts and constructs, so please bear that in mind. Thank you for your assistance!

If your document is well structured and in order, this should do the trick:

$name=array();
$surname=array();

foreach($html->find('span[class="given-name"]') as $e){
    $name[]=$e->innertext;
}

foreach($html->find('span[class="family-name"]') as $e){
    $surname[]=$e->innertext;
}

foreach($name as $key=>$value){
  echo $name[$key] . " " . $surname[$key] . "<br>";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM