[英]looping over an array of arrays
I need to loop over an array like this: 我需要遍历这样的数组:
{
"tipo": "AFO",
"codigo": "xxx",
"nombre": "xxx Organización",
"contenidos": [
{
"tipo": "MOD",
"codigo": "xxx",
"nombre": "Organización ...",
"contenidos": [
{
"tipo": "UFO",
"codigo": "xxxx",
"nombre": "Gestión Económico Actividad...",
"contenidos": [
{
"tipo": "UDI",
"codigo": "xxx",
"nombre": "Presupuestos y contabilidad básica de la actividad comercial",
"esudi": "1",
"contenidos": [
{
"tipo": "empty",
"codigo": "empty",
"nombre": "Contenidos",
"contenidos": [
{
"tipo": "HTM",
"codigo": "xxx",
"nombre": "INTRODUCCIÓN"
},
{
"tipo": "HTM",
"codigo": "xxxxx",
"nombre": "OBJETIVOS"
},
{
"tipo": "HTM",
"codigo": "xxxx",
"nombre": "MAPA CONCEPTUAL"
},
{
"tipo": "HTM",
"codigo": "xxx",
"nombre": "1. Concepto y finalidad del presupuesto",
"contenidos": [
{
"tipo": "HTM",
"codigo": "xxx",
"nombre": "1.1. El proceso presupuestario"
},
{
"tipo": "HTM",
"codigo": "xxx",
"nombre": "1.2. Usos, objetivos y funciones del presupuesto"
},
{
"tipo": "HTM",
"codigo": "xxx",
"nombre": "1.3. Clases de presupuestos: de inversión, de ventas, de control"
}
]
},
{
"tipo": "HTM",
"codigo": "xxxx",
"nombre": "2. Clasificación de los presupuestos",
"contenidos": [
{
"tipo": "HTM",
"codigo": "xxxxx",
"nombre": "2.1. El pronóstico de ventas"
},
{
"tipo": "HTM",
"codigo": "xxx",
. 。 . 。 . 。 . 。
The main issue resides in the attribute called contenidos , because I receive this array from a web service, and it's dinamyc, and I don't know the depth of this array (arrays of arrays...) I'm trying with foreach but I'm mired... 主要问题在于名为contenidos的属性 ,因为我从Web服务接收到此数组,但它是dinamyc,并且我不知道此数组(数组的数组...)的深度。我陷入困境...
This is what I have right now: 这就是我现在所拥有的:
foreach($curso as $key => $value){
echo "clave : " .$key. " , valor : " .$value. "<br>";
if(is_array($value)){
foreach($value as $key2 => $value2){
echo "clave : " .$key2. " , valor : " .$value2. "<br>";
}
}
}
Any help is welcomed. 欢迎任何帮助。 Thanks, 谢谢,
Try putting it in a specific function/method like this: 尝试将其放在特定的函数/方法中,如下所示:
function iterateMe($curso)
{
foreach ($curso as $key=>$value) {
// First check if the value as an array
if (is_array($value)) {
// Yes! Let's iterate through it
iterateMe($value);
} else {
// No! Just display the values
echo sprintf("clave: %s, valor: %s <br>", $key, $value);
}
}
}
iterateMe($curso);
Use this function to find the depth of the array: 使用此函数查找数组的深度:
function array_depth(array $array) {
$max_depth = 1;
foreach ($array as $value) {
if (is_array($value)) {
$depth = array_depth($value) + 1;
if ($depth > $max_depth) {
$max_depth = $depth;
}
}
}
return $max_depth;
}
Then you can do a simple for-loop to iterate over every array: 然后,您可以执行一个简单的for循环来遍历每个数组:
for ($i = 1; $i <= $max_depth; $i++)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.