Foreach only finds the last element of an array
I am trying to get all the values of my array, but I only get the last element.
(last description and last link).
here is the code:
$content = str_get_html($html);
$links = $content->find('.myclass a');
foreach($links as $k => $v)
{
$descr= $v-> plaintext;
$link_to= $v->href;
$a=array(
1 => $descr,
2 => $link_to);
}
return a$;
how can i encode a complete array?
+3
source to share
1 answer
You are overwriting the same array in every loop. You need to add another dimension:
$content = str_get_html($html);
$links = $content->find('.myclass a');
$a = array();
foreach($links as $k => $v) {
$descr = $v->plaintext;
$link_to = $v->href;
$a[] = array(1 => $descr, 2 => $link_to);
// ^ add another dimension
// DONT USE THIS! You are overwriting it every loop
// $a = array(1 => $descr, 2 => $link_to);
}
// return a$; ? a$ maybe `$a`
+4
source to share