Skip to content

Instantly share code, notes, and snippets.

@arcanisgk
Created October 5, 2021 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arcanisgk/1ee76878fde51963d51e8d73c4b0b58d to your computer and use it in GitHub Desktop.
Save arcanisgk/1ee76878fde51963d51e8d73c4b0b58d to your computer and use it in GitHub Desktop.
¿Cómo acceder a un valor de un array asociativo dentro de otro?
***Primero:***
para lograr esa estructura tu variable debe ser un array antes de iniciar la asignación de datos entonces te falta esto, la declaración:
$Ibex35=[];
También es importante que comprender que la variable `$numeroEmpresa` debe ser inicializada en 1 ya que no me confirmaste en los comentario como es la estructura numérica, en mi ejemplo iría de la empresa #1 a la #35.
entonces yo usaría los siguiente:
<?php
$nombre="E";
$numeroEmpresa=1;
$i=0;
$Ibex35 = []; //te falta esto
while ($i<35) {
$i++;
$Ibex35[$nombre.$numeroEmpresa] = [
"Precio" => rand(),
"VARIACION(%)" => rand(),
"VARIACION(euros)" => rand(),
"VOLUMEN" => rand(),
];
$numeroEmpresa++;
};
echo "<pre>";
echo var_export($Ibex35['E35'], true);
echo "</pre>";
/**
* o si tienes los datos en variables puedes hacer esto:
*/
$num=35;
echo "<pre>";
echo var_export($Ibex35['E'.$num]['Precio'], true);
echo "</pre>";
/**
* y si imprimes la variable completa veras que tendras todos los datos:
*/
echo "<pre>";
echo var_export($Ibex35, true);
echo "</pre>";
**Output #1 y 2:**
[![introducir la descripción de la imagen aquí][1]][1]
**Output #3:**
[![introducir la descripción de la imagen aquí][2]][2]
***El siguiente nivel, emplea una funcion:*** con esta buena practica tu código es funcional y mantenible, no requiere usar de variables ni contadores.
<?php
function get_values(){
return [
'Precio' => rand(),
'VARIACION(%)' => rand(),
'VARIACION(euros)' => rand(),
'VOLUMEN' => rand(),
];
}
$prefix="E";
$range=range(1,35);
$Ibex35 = [];
foreach($range as $key){
$Ibex35[$prefix.$key]=get_values();
}
echo "<pre>";
echo var_export($Ibex35['E35'], true);
echo "</pre>";
***El siguiente nivel: implementando: `array_map`, `array_walk` y `array_flip`***
<?php
function updateIndex(&$element, $clave, $prefijo){
$element = $prefijo.$element;
}
function get_values(&$element, $clave){
$properties = ['Precio'=>0,'VARIACION(%)'=>0,'VARIACION(euros)'=>0,'VOLUMEN'=>0];
//mapeamos las propiedades y les asignamos un valor rand()
$element = array_map(function() {
return rand();
},$properties);
}
$prefix='E';
$Ibex35=range(1,35);
array_walk($Ibex35,'updateIndex',$prefix); //agregamos el prefijo
$Ibex35=array_flip($Ibex35); //invertimos los datos.
array_walk($Ibex35,'get_values'); //insertamos las propiedades.
echo "<pre>";
echo var_export($Ibex35, true);
echo "</pre>";
para esta ultima opción el resultado es el mismo que el output 1, 2 y 3.
***Versión con resultado y acceso OOP***
También para concluir sobre la forma de acceder a datos en un array se suele usar el casteo a objeto mayormente visto en la programación orientada a objeto (OOP):
<?php
function updateIndex(&$element, $clave, $prefijo){
$element = $prefijo.$element;
}
function get_values(&$element, $clave){
$properties = ['Precio'=>0,'VARIACION(%)'=>0,'VARIACION(euros)'=>0,'VOLUMEN'=>0];
$element = array_map(function() {
return rand();
},$properties);
}
$prefix='E';
$Ibex35=range(1,35);
array_walk($Ibex35,'updateIndex',$prefix); //agregamos el prefijo
$Ibex35=array_flip($Ibex35); //invertimos los datos.
array_walk($Ibex35,'get_values');
//con json_encode casteamos el array a un string.
//luego con json_decode casteamos el string en un objeto.
$Ibex35=json_decode(json_encode($Ibex35));
echo "<pre>";
echo var_export($Ibex35->E1->Precio); //acceso al dato como propiedad.
echo "</pre>";
*Espero mi respuesta solucione tu duda y amplié tus conocimiento en el manejo de array.*
***Documentación asociada:***
[Crear Array Multidimensional con loop while.][3]<br>
[Ejecute la función PHP en While Loop][4]<br>
[Uso de variables por Referencia `&$foo`][5]<br>
[Método de php: `array_map`][6]<br>
[Método de php: `array_walk`][7]<br>
[Método de php: `array_flip`][8]<br>
[Castear Array a Un String type JSON con `json-encode`.][9]<br>
[Castear String type JSON a un Objeto con `json-decode`.][10]<br>
[1]: https://i.stack.imgur.com/NhtgL.png
[2]: https://i.stack.imgur.com/w54kt.png
[3]: https://stackoverflow.com/a/11663331/4717133
[4]: https://stackoverflow.com/a/30427764/4717133
[5]: https://www.php.net/manual/es/language.references.php
[6]: https://www.php.net/manual/es/function.array-map.php
[7]: https://www.php.net/manual/es/function.array-walk.php
[8]: https://www.php.net/manual/es/function.array-flip.php
[9]: https://www.php.net/manual/es/function.json-encode.php
[10]: https://www.php.net/manual/es/function.json-decode.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment