doulian4762 2019-05-28 19:54
浏览 65
已采纳

对多个多维数组执行相同的逻辑

I'm currently trying the following:

I have multiple arrays defined. They all are filled by fetching data from the database, so they all contain the same columns/data structure, but with different data. For example, lets say the arrays are different schools, so there is:

//pseudoCode:
array1 = ({"Name: Peter", "Surname: not peter"},{"Name: doe", "Surname: john"});
array2 = ({"Name: asfwe", "Surname: qwfqwf"},{"Name: asfas", "Surname: fsbng"});
array3 = ({"Name: weqw", "Surname: wqeqewqw"},{"Name: doqweqwee", "Surname: wewe"});

Now, for all these arrays, I want to do the same things. In my case, I have multiple if else cases, checking the length of the array and doing some stuff.

So far I'm only doing it for array 1 though. Now my first idea was to simply copy the logic and refactor all variable names to array2 respectively to array3, but this wouldn't make sense, because in my real case, its 10 arrays instead of 3 and the logic is about 150 lines of code, so I would have a lot of duplicate code and would need to change it everywhere, if something in the logic changes.

Now the question is: How can I do the same procedure for every array?

So what I would need is something like:

//pseudoCode again
foreach(array in array1, array2, array3, array4, array5,....){
//do something with variable "array", which is actually one of the defined arrays
}

A hint in the right direction would be great.

Thank you in advance.

  • 写回答

1条回答 默认 最新

  • dongliuzhuan1219 2019-05-28 20:03
    关注

    Procedure code demand exporting logic to function:

    function foo($array) {
        // modify the array or do what ever you need
        return $array; // in case it has been modify
    }
    

    Now can you function as:

    foreach($arrays as &$arr)
        $arr = foo($arr); // calling the function on each array
        // the re-assign is just in case it has been modify
    

    In this example $arrays stand for array with all your inner arrays as:

    $arrays = array($array1, $array2, $array3, ...) 
    

    if your array as getting dynamicly from some other function / SQL code do:

    $arrays = []; // init empty array
    while (@SOME_CONDITION@) {
        $arrays[] = getAnotherArrayFunction(); // append the array to your array
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条