Php阵列数组得到了正确的结果

时间:2017-02-21 10:12:30

标签: php arrays loops

我想迭代数组阵列。 我有什么:

$params =  [
 'regs' => [156, 154, 138, 132, 142, 144],
 'axis' => [0, 0, 0, 0, 0, 0],
 'visible' => [1, 1, 0, 1, 0, 0],
 'dependencies' => [1, 1, 1, 1, 1, 1],
];

我想得到什么:

foreach() {
 foreach() {
  render_element(reg = 156, axis = 0, visible = 1, dep = 1);
  *render_element(reg = 154, axis = 0, visible = 1, dep = 1);
  *render_element(reg = 138, axis = 0, visible = 0, dep = 1); etc
 }
}

3 个答案:

答案 0 :(得分:3)

您可能希望在第一个regs数组中进行迭代,并使用相同的键从其他数组中打印值,因为键看起来完全相同,如下所示

foreach($params['regs'] as $key => $val) {
    echo 'render_element(reg ='. $val.', axis ='. $params['axis'][$key].', visible ='. $params['visible'][$key].', dep ='.$params['dependencies'][$key].');' . "\n";  
}

这将打印

render_element(reg =156, axis =0, visible =1, dep =1);
render_element(reg =154, axis =0, visible =1, dep =1);
render_element(reg =138, axis =0, visible =0, dep =1);
render_element(reg =132, axis =0, visible =1, dep =1);
render_element(reg =142, axis =0, visible =0, dep =1);
render_element(reg =144, axis =0, visible =0, dep =1);

live demo

答案 1 :(得分:0)

如果您确定,params中的所有数组都具有相同的长度,您可以使用常规for循环:

for($i=0; $i<count($params["regs"]); ++$i)
{
    render_element($params["regs"][i],
    $params["axis"][i],
    $params["visible"][i],
    $params["dependencies"][i])
}

答案 2 :(得分:0)

Heii MaoStrean

检查foreach-loop的语法:http://php.net/manual/en/control-structures.foreach.php