简体   繁体   中英

I'm pulling my hair out with basic error

I think i'm to old or i'm just stupid but i can't understand why i can't loop on an simple array.

I have this code:

$results = [];
for ($i = 0; $i < count($links); $i++) {
   $results[] = [
      'site' => $links[$i],
      'pda'  => $data[$i]->pda
   ];
}

The $links array contains a list of urls and $data contains a list of values like this:

array(3) {
  0 =>  object(stdClass) 
    {
      "pda" => int 100
    }
  1 =>  object(stdClass) 
    {
      "pda" => int 100
    }
  2 =>  object(stdClass) 
    {
      "pda" => int 1
    }
}

EDIT: This is the print_r($data) content...it seems that some of you don't understand the dump from above and prefer the print_r solution :-|

Array
(
    [0] => stdClass Object
        (
            [pda] => 100
        )

    [1] => stdClass Object
        (
            [pda] => 1
        )

    [2] => stdClass Object
        (
            [pda] => 100
        )

)

If i do $data[$i]->pda in the loop i get "Cannot use object of type stdClass as array" error.

If i try to access it as an object, i get "Trying to get property of non-object" error.

Bottom line, am i stupid or i'm going crazy?!

Thank you!

Little bit extended answer from comments:

You probably have a different number of $links than $data . Debug with a simple if else condition before accessing $data[$i] and dump the actual result if it fails.

for ($i = 0; $i < count($links); $i++) {
  if (isset($data[$i])) {
      $results[] = [
       'site' => $links[$i],
       'pda'  => $data[$i]->pda
    ];
  } else {
    // Somethings wrong
    var_dump($i);
    var_dump($links);
    var_dump($data);
  }

}

So if your function gets called several times, you are dumping the actual data when the error happens.

According to your structure:

Array
(
    [0] => stdClass Object
        (
            [pda] => 100
        )

    [1] => stdClass Object
        (
            [pda] => 1
        )

    [2] => stdClass Object
        (
            [pda] => 100
        )

)

And your calling structure:

$data[$i]->pda

Here you call in wrong way, $i is not array its a stdclass object array, try by this:

$data->$i['pda'].

By this $data watching into your stdclass object array and then "pda" calls as an array for that.

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