简体   繁体   English

PHP根据值连续循环遍历数组

[英]PHP Loop through arrays consecutively based on value

I'm having a looping mind-breaking issue which I can't seem to solve myself.我有一个循环的令人心碎的问题,我似乎无法自己解决。 Currently working on saving a form input in a webshop.目前致力于在网上商店中保存表单输入。 The data:数据:

"personalisation" => array:3 [▼
    0 => "embroidery"
    1 => "printing"
    2 => "embroidery"
  ]
 "repeat" => array:2 [▼
    0 => "true"
    1 => "true"
  ]
"selectedColors" => array:1 [▼
    0 => "3"
  ]

The problem which I have here: I need to loop through the personalisation array to add to my DB.我在这里遇到的问题:我需要遍历个性化数组以添加到我的数据库中。 With the embroidery, the repeat value is linked and for the printing the selectedColors is linked.对于刺绣,重复值是链接的,并且对于打印,selectedColors 是链接的。 How can I loop through the personlisation array and match the values from the other array?如何遍历个性化数组并匹配另一个数组中的值?

I really wouldn't recommend designing forms like this, you're basically just sending a jumbled mess to your backend with no association.我真的不建议设计这样的表单,您基本上只是在没有关联的情况下向后端发送一团乱麻。

You can "correct" the association by filtering the personalisation array and reindexing it so the keys match the other arrays.您可以通过过滤个性化数组并重新索引它来“纠正”关联,以便键与其他数组匹配。

$embroderies = array_values(array_filter($array['personalisation'], function($item) {
   return $item === 'embroidery';
}));

foreach($emborderies as $key => $value) {
    // get value from $array['repeat'][$key];   
}

I can't think of any other way than to use a helper array for example.例如,除了使用辅助数组之外,我想不出任何其他方法。

It could be array('embroidery' => 'repeat', 'printing' => 'selectedColors')它可以是 array('embroidery' => 'repeat', 'printing' => 'selectedColors')

And you start looping through personalization, depending on the value you use it as a key in the helper array, then finally get the wanted value from the array.然后您开始遍历个性化,具体取决于您将其用作辅助数组中的键的值,然后最终从数组中获取所需的值。

1st iteration: 0/embroidery -> embroidery/repeat -> repeat/true第一次迭代:0/刺绣 -> 刺绣/重复 -> 重复/真

2nd iteration: 1/printing -> printing/selectedColors -> selectedColors/ ...第二次迭代:1/printing -> Printing/selectedColors -> selectedColors/ ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM