![](/img/trans.png)
[英]How to GET array values from JavaScript and display the same values in php
[英]PHP get ranges of same values from array
有没有办法获得相同值的键范围并创建一个新数组?
假设我们在php中有一个像这样的数组:
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b','6'=>'a','7'=>'a'];
我怎样才能得到这个数组? 有什么功能吗?
$second_array = ['1-3'=>'a','4-5'=>'b','6-7'=>'a'];
遍历它,提取键,生成范围并插入新数组-
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b'];
$flip = array();
foreach($first_array as $key => $val) {
$flip[$val][] = $key;
}
$second_array = [];
foreach($flip as $key => $value) {
$newKey = array_shift($value).' - '.end($value);
$second_array[$newKey] = $key;
}
输出量
array(2) {
["1 - 3"]=>
string(1) "a"
["4 - 5"]=>
string(1) "b"
}
关于第一个问题,您可以使用foreach()循环获取每个值的范围。
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b'];
foreach($first_array as $key=>$value)
{
//do your coding here, $key is the index of the array and $value is the value at that range, you can use that index and value to perform array manipulations
}
关于您的第二个问题,目前尚不清楚正在尝试实施的内容。 但是您想要做的事情,例如创建带有修改后的索引的新数组等,都可以在此foreach()
循环本身中完成
我希望这可以帮助你。
如果有人仍在寻找答案,这就是我所做的。 给定数组
$first_array = ['0'=>'a',
'1'=>'a',
'2'=>'a',
'3'=>'a',
'4'=>'a',
'5'=>'b',
'6'=>'b',
'7'=>'a',
'8'=>'a']
我构建了一个多维数组,其中每个元素都是另外三个元素的数组:
[0] - The value in the first array
[1] - The key where the value starts repeating
[2] - The last key where the value stops repeating
编码
$arrayRange = [];
for($i = 0; $i < count($first_array); $i++){
if(count($arrayRange) == 0){
// The multidimensional array is still empty
$arrayRange[0] = array($first_array[$i], $i, $i);
}else{
if($first_array[$i] == $arrayRange[count($arrayRange)-1][0]){
// It's still the same value, I update the value of the last key
$arrayRange[count($arrayRange)-1][2] = $i;
}else{
// It's a new value, I insert a new array
$arrayRange[count($arrayRange)] = array($first_array[$i], $i, $i);
}
}
}
这样,您将获得一个多维数组,如下所示:
$arrayRange[0] = array['a', 0, 4];
$arrayRange[1] = array['b', 5, 6];
$arrayRange[2] = array['a', 7, 8];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.