Jump to content

Recommended Posts

Hello. 

I was wondering if anyone could please help with a problem I seem to be having a problem with my foreach loops. I have an array that holds other arrays. When I am trying to populate the database tables with the information in each array, things are going horribly wrong.

This is my code:

$tabledata = $this->db->get('tableinfo');

$i = 0;
$_temp = array();
foreach($tabledata->result() as $row) {
	$data[$i] = $this->callAPI("lateststandings&records=3&category=" . $row->category . "&distance=" . $row->distance_id);
	array_push($_temp, $row->dbname);
	$i++;
}

$j = 0;
foreach($data[$j]['Records']['Record'] as $record) {
	$record['FirstName'] .= " " . $record['LastName'];
	$this->db->replace($_temp[$j], $record);
	$j++;
}

 

When this is run 2 things are happening:

1) What I am expecting to happen is, there should be 3 rows added to each table. But only 1 is being added to each table.
2) The 3 rows that are being created (1 in each table), are the 3 rows I am expecting to see in the first table.

I am not sure what I am doing wrong in these loops.

 

Link to comment
https://forums.phpfreaks.com/topic/309966-foreach-loop-problem/
Share on other sites

I don't think you're using the right index for the foreach(). Loop through $data itself, then get the value of ['Records']['Record'] of the current iteration. What you're doing right now is looping through $data[0]['Records']['Record'] - first off, you're specifically telling the program to loop through only the first index of $data, then you're telling it to loop only through the ['Records']['Record'] index of that first index. That may be correct (it's difficult to tell without seeing the data source) but it sounds off.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.