![](/img/trans.png)
[英]PHP bidimensional associative array of two different associative arrays how to foreach just one of the two
[英]PHP: How to store values from a big (bidimensional) array into different arrays in a foreach loop
我有一个数组,其中每个键都有另一个数组。 我想做的是将这些值存储在不同的数组中。 例如,原始数组如下所示:
Array
(
[0] => Array
(
[concurso] => 2758
[R1] => 12
[R2] => 20
[R3] => 33
[R4] => 46
[R5] => 50
[R6] => 51
[R7] => 54
)
[1] => Array
(
[concurso] => 2759
[R1] => 12
[R2] => 15
[R3] => 31
[R4] => 50
[R5] => 54
[R6] => 55
[R7] => 11
)
[2] => Array
(
[concurso] => 2760
[R1] => 4
[R2] => 11
[R3] => 12
[R4] => 40
[R5] => 45
[R6] => 51
[R7] => 55
)
.
.
.
[29] => Array
(
[concurso] => 2787
[R1] => 3
[R2] => 5
[R3] => 19
[R4] => 24
[R5] => 28
[R6] => 30
[R7] => 15
)
)
对于每个键,我想将对应的值存储在不同的数组中(其中“ concurso”将是每个新数组的键及其对应的Rn值):
R1:
Array
(
[2758] => 12
[2759] => 12
[2760] => 4
...
[2787] => 3
)
R2:
Array
(
[2758] => 20
[2759] => 15
[2760] => 11
...
[2787] => 5
)
R3:
Array
(
[2758] => 33
[2759] => 31
[2760] => 12
...
[2787] => 19
)
R4:
Array
(
[2758] => 46
[2759] => 50
[2760] => 40
...
[2787] => 24
)
R5:
Array
(
[2758] => 50
[2759] => 54
[2760] => 45
...
[2787] => 28
)
R6:
Array
(
[2758] => 51
[2759] => 55
[2760] => 51
...
[2787] => 30
)
...
Rn:
我该如何实现? 我猜我需要动态创建变量名,因为给定数组的元素数可能会根据检索到的数据而变化。 你有什么建议?
我正在尝试此代码,但到目前为止没有运气:
$ultimos_sorteos_m,true); //this is the big array shown above
foreach($ultimos_sorteos_m as $key1 => $last_sorteos){
$contador=count($last_sorteos); //how many items the current sub-array has
$k=1; //an index
echo '<p>the number of items is '.$contador.'</p>';
foreach($last_sorteos as $key=>$valor){
if($key=='concurso'){
$concurso=$valor;
echo 'concurso: '.$concurso.' <br>'; //to get the 'concurso' that will work as a key for the other arrays
}
//storing here the rest of the values
if(substr( $key, 0, 1 ) === "R" && substr($key, 1, 1)===$k){
//i don't know here how to store the values in different arrays
echo 'storing value: '.$valor.'<br>';
$Ritems[$concurso]=$valor; //the problem is that only store the last value
}
}
}
如果您想知道为什么,我希望以此方式通过使用phpgraphlib图形库对这些数据进行图形化。 这将是显示不同线条的图形。
像这样?
foreach($orig_array[0] as $key => $_)
$new_array[$key] = array_column($orig_array, $key, 'concurso');
如果您绝对确定需要R1
, R2
作为变量 (不需要),则可以在以后extract()
数组。
试试看:这会动态创建变量名,因此您无需知道R1,R2,R3等元素的编号
<?php
foreach($ultimos_sorteos_m[0] as $key1 => $last_sorteos){
$$key1 = array_column($ultimos_sorteos_m, $key1 , 'concurso'); // This is a dynamic variable name. See http://php.net/manual/en/language.variables.variable.php
}
var_dump($R1);
var_dump($R2);
?>
如果您发现问题,请发表评论。 谢谢!
您可以使用array_column
。 如果您的PHP
版本5.5+,请尝试此操作
$R1 = array_column($arr, 'R1', 'concurso');
.
.
.
$R7 = array_column($arr, 'R7', 'concurso');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.