在此示例中如何使用嵌套循环?

时间:2019-10-16 12:16:23

标签: php loops logic

考虑以下$data数组:

Array
(
    [0] => Array
        (
            [code] => 20
            [name] => Name 1
            [month] => 4
            [cost] => 100
            ..
            ..
        )

    [1] => Array
        (
            [code] => 30
            [name] => Name 2
            [month] => 3
            [cost] => 120
            ..
            ..
        ) 

    [1] => Array
        (
            [code] => 30
            [name] => Name 2
            [month] => 6
            [cost] => 180
            ..
            ..
        )    

    ..
    ..
)

每个数组可以具有未知数量的代码。每个代码都有不同的月份ID。我想对数据进行排序和显示,以便每个代码只有一行,然后在该行中,在等于月份的列号中显示[cost]的值。例如:

Column      1     2     3     4     5     6     7     8     9     10     11    12
Name 1                       100
Name 2                  120               180

这是我要尝试的:

为了找出应该打印多少行,我获取了唯一的代码值:

$codes = array();                   
foreach( $data as $row ){ 
    if ( in_array($row['code'], $codes) ) {
        continue;
    }
    $codes[] = $row['code'];
}

接下来,我使用循环来打印行:

foreach( $codes as $code ){

    //print 12 columns for each othe row
    for ($i = 1; $<=12; $i++) {

        //display column value if the code is same as the row
        //and the month value is same as $i
        //here's the problem
        if (( $data['code'] == $code ) &&( $data['month'] == $i )) {
            echo $data['cost'];
        }

    }
}

问题/问题: 我是否需要在for循环中放入另一个循环以检查$data['code'] == $code是否存在?或者我该怎么做?

2 个答案:

答案 0 :(得分:1)

我建议您先将数据预处理到结构化数组中,然后再打印,例如,通过具有以下结构的代码索引:

 `cannot copy sequence with size 3 to array axis with dimension 14400`

您可以这样做:

ValueError                                Traceback (most recent call last)
<command-3171623043129929> in <module>()
----> 1 ds_telemetry_pd.apply(apply_calc_coef, axis=1)

/databricks/python/lib/python3.5/site-packages/pandas/core/frame.py in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)
   4150                     if reduce is None:
   4151                         reduce = True
-> 4152                     return self._apply_standard(f, axis, reduce=reduce)
   4153             else:
   4154                 return self._apply_broadcast(f, axis)

/databricks/python/lib/python3.5/site-packages/pandas/core/frame.py in _apply_standard(self, func, axis, ignore_failures, reduce)
   4263                 index = None
   4264 
-> 4265             result = self._constructor(data=results, index=index)
   4266             result.columns = res_index
   4267 

/databricks/python/lib/python3.5/site-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
    264                                  dtype=dtype, copy=copy)
    265         elif isinstance(data, dict):
--> 266             mgr = self._init_dict(data, index, columns, dtype=dtype)
    267         elif isinstance(data, ma.MaskedArray):
    268             import numpy.ma.mrecords as mrecords

/databricks/python/lib/python3.5/site-packages/pandas/core/frame.py in _init_dict(self, data, index, columns, dtype)
    400             arrays = [data[k] for k in keys]
    401 
--> 402         return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
    403 
    404     def _init_ndarray(self, values, index, columns, dtype=None, copy=False):

/databricks/python/lib/python3.5/site-packages/pandas/core/frame.py in _arrays_to_mgr(arrays, arr_names, index, columns, dtype)
   5401 
   5402     # don't force copy because getting jammed in an ndarray anyway
-> 5403     arrays = _homogenize(arrays, index, dtype)
   5404 
   5405     # from BlockManager perspective

/databricks/python/lib/python3.5/site-packages/pandas/core/frame.py in _homogenize(data, index, dtype)
   5712                 v = lib.fast_multiget(v, oindex.values, default=NA)
   5713             v = _sanitize_array(v, index, dtype=dtype, copy=False,
-> 5714                                 raise_cast_failure=False)
   5715 
   5716         homogenized.append(v)

/databricks/python/lib/python3.5/site-packages/pandas/core/series.py in _sanitize_array(data, index, dtype, copy, raise_cast_failure)
   2950             raise Exception('Data must be 1-dimensional')
   2951         else:
-> 2952             subarr = _asarray_tuplesafe(data, dtype=dtype)
   2953 
   2954     # This is to prevent mixed-type Series getting all casted to

/databricks/python/lib/python3.5/site-packages/pandas/core/common.py in _asarray_tuplesafe(values, dtype)
    390             except ValueError:
    391                 # we have a list-of-list
--> 392                 result[:] = [tuple(x) for x in values]
    393 
    394     return result

ValueError: cannot copy sequence with size 3 to array axis with dimension 14400 ```

您可以使用类似于以下的功能进行打印:

[
  ['the code'] => [
     'name' => '',
     'months' => [ 
        '6' => // cost
     ]
  ]
]

哪个输出:

$items = [
    [
        'code' => 20,
        'name' => 'Name 1',
        'month' => 4,
        'cost' => 100,
    ],
    [
        'code' => 30,
        'name' => 'Name 2',
        'month' => 3,
        'cost' => 120,
    ],
    [
        'code' => 30,
        'name' => 'Name 2',
        'month' => 6,
        'cost' => 180,
    ],
];

$sortedItems = [];
foreach ($items as $item) {
    if (!isset($sortedItems[$item['code']])) {
        $sortedItems[$item['code']] = [
            'name' => $item['name'],
            'months' => [],
        ];
    }

    $sortedItems[$item['code']]['months'][$item['month']] = $item['cost'];
}

答案 1 :(得分:1)

我将使用一个循环来重新索引数组:

$list = $codes = [];
for ($array as $item){
    $list[$item['code']][$item['month']] = $item;
    $codes[$item['code']] = $item['name'];
}

然后使用两个循环进行打印:

for ($codes as $code => $codeName){
    echo '<tr><th>', $codeName, '</th>';
    for (range(1, 12) as $month){
        echo '<td>', ($list[$code][$month]['cost'] ?? ''), '</td>;
    }
    echo '</tr>', "\n";
}

我真的不喜欢循环中使用if()的想法。