0
\$\begingroup\$

I have such a problem:

I'm parsing a lot of HTML files with Simple HTML DOM Parser, that's why I need to use three foreachs to parse the necessary information from it -> I am getting a lot of information and now I have three arrays which keep it. I think that it's dumb to keep the code like that and I want to keep the information in the class.

How can I do it in a right way? I really need your advice to have a good code in the future

Here is the code with three arrays:

if(count($infos->find('.products-list-item')))
{
    foreach ($infos->find('.products-list-item product-label, .products-list-item .products-list-item__brand, .products-list-item .products-list-item__type,.products-list-item .price') as $item_info) 
    {
        $item_info_arr[] = $item_info->plaintext;
        $i=0;
    }

    foreach ($infos->find('.products-list-item__img') as $img) 
    {
        $src_arr[] = $img->src;
    }

    foreach ($infos->find('.products-list-item .products-list-item__sizes') as $sizes_info) 
    {
        while($size = $sizes_info->children($k++))
        {
            $sizes_arr[] = $size->plaintext;
        }

        $k=0;
    }   

} else {echo "not found";}

But what can I do, then?

\$\endgroup\$
2
\$\begingroup\$

Please provide some more information, like the example contents of $infos. It is hard to find any other solution if we are not able to understand your current solution in the first place.

However, there already are some issues with your code:

  • avoid using variable names like $i and $k. They should be named according to their meaning (see example for $k)
  • $i seems not to be read in your code
  • $k and all arrays seem to be used uninitialized

Your while loop seems a bit too clever to me. All you want to do is iterate $k so you should instead use a for loop:

for($childIndex = 0; $size = $sizes_info->children($childIndex); ++$childIndex)
    $sizes_arr[] = $size->plaintext;

The foreach loops look as if they could be better implemented by array_map:

$item_infos = $infos->find('.products-list-item product-label, .products-list-item .products-list-item__brand, .products-list-item .products-list-item__type,.products-list-item .price');
$get_plaintext = function($item_info) { return $item_info->plaintext; };
$item_info_arr = array_map($get_plaintext, $item_infos); 

A foreach loop could be as readable however then you should at least use named variables (like $item_infos but with better names (I have no idea what this find returns)) to keep the head of the loop short and readable.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.