我有多个数组并且所有数组的计数相等,我想通过索引循环的问题, 喜欢从第一个数组 fiscal_year 中的索引0开始 然后转到索引为0的第二个数组收入 完成后,再次开始循环索引1
它就像行一样,每一行都会像这样
1996-12 | 101.2
1997-12 | 249.801
array(15) {
["fiscal_year"]=>
array(21) {
[0]=>
string(7) "1996-12"
[1]=>
string(7) "1997-12"
[2]=>
string(7) "1998-12"
[3]=>
string(7) "1999-12"
[4]=>
string(7) "2000-12"
[5]=>
string(7) "2001-12"
[6]=>
string(7) "2002-12"
[7]=>
string(7) "2003-12"
[8]=>
string(7) "2004-12"
[9]=>
string(7) "2005-12"
[10]=>
string(7) "2006-12"
[11]=>
string(7) "2007-12"
[12]=>
string(7) "2008-12"
[13]=>
string(7) "2009-12"
[14]=>
string(7) "2010-12"
[15]=>
string(7) "2011-12"
[16]=>
string(7) "2012-12"
[17]=>
string(7) "2013-12"
[18]=>
string(7) "2014-12"
[19]=>
string(7) "2015-12"
[20]=>
string(3) "TTM"
}
["revenue"]=>
array(21) {
[0]=>
string(5) "101.2"
[1]=>
string(7) "249.801"
[2]=>
string(7) "493.699"
[3]=>
string(7) "548.891"
[4]=>
string(7) "543.159"
[5]=>
string(7) "536.404"
[6]=>
string(7) "474.765"
[7]=>
string(7) "509.099"
[8]=>
string(7) "588.991"
[9]=>
string(7) "643.405"
[10]=>
string(7) "732.012"
[11]=>
string(6) "808.35"
[12]=>
string(7) "777.969"
[13]=>
string(7) "758.925"
[14]=>
string(7) "773.743"
[15]=>
string(7) "652.235"
[16]=>
string(7) "650.632"
[17]=>
string(7) "667.031"
[18]=>
string(7) "636.799"
[19]=>
string(7) "594.883"
[20]=>
string(7) "594.883"
}
我的代码是这样的,它不能正常工作,它插入第一行并停止
for ($x = 0; $x <= count($company_data['fiscal_year']); $x++) {
foreach ($company_data as $key => $value) {
foreach($value as $key2 => $value2){
$this->db->set('company_name', $this->input->post('company_name'));
$this->db->set('company_code', $this->input->post('company_code'));
$this->db->set('company_hide', 1);
$this->db->set('company_created', time());
$this->db->set($key,$value2);
break;
}
}
$this->db->insert('d_company');
}
答案 0 :(得分:2)
您只需要一个for
循环,而不是三个嵌套循环:
for ($x = 0; $x < count($company_data['fiscal_year']); $x++) {
$fiscal_year = $company_data['fiscal_year'][$x];
$revenue = $company_data['revenue'][$x];
print "$fiscal_year: $revenue\n";
}
产生:
1996-12: 101.2
1997-12: 249.801
1998-12: 493.699
1999-12: 548.891
2000-12: 543.159
2001-12: 536.404
2002-12: 474.765
2003-12: 509.099
2004-12: 588.991
2005-12: 643.405
2006-12: 732.012
2007-12: 808.35
2008-12: 777.969
2009-12: 758.925
2010-12: 773.743
2011-12: 652.235
2012-12: 650.632
2013-12: 667.031
2014-12: 636.799
2015-12: 594.883
TTM: 594.883
答案 1 :(得分:0)
你首先需要有一个foreach然后是可选循环(while,for等),如
$to_update = '';
foreach($company_data as $item){
$count = count($item);
for($i = 0; $i <= $count; $i++){
switch($item[$i]){
case 'company_name':
$to_update .= $item[$i] . ' => ' . $this->input->post('value') . ',';
break;
case 'company_hide':
$to_update .= $item[$i] . ' => 1,';
break;
case 'company_created':
$to_update .= $item[$i] . ' => ' . $time() . ',';
break;
default:
$to_update .= $item[$i] . ' => ' . $this->input->post('value') . ',';
break;
}
}
$this->model->upate($to_update);