Create an array in PHP

-1

Hello actulemnte I have a doubt this is my code php to make my array:

<?php

$tra = new area();
$madres = $_POST['mesa'];
$reg = $tra->traer_area($madres);
if (count($reg) == 0) {
    $data['data'] = array();
} else {
    for ($i = 0; $i < count($reg); $i++) {
        $data['data'] = $reg;
    }
}
print_r($data);
?>

And the result is:

Array ( [data] => Array ( [0] => Array ( [nombre_completo] => YOLANDA MEJIA ROJAS ) [1] => Array ( [nombre_completo] => IRMA VARA SANCHEZ ) [2] => Array ( [nombre_completo] => DIANA AGUAYO MORENO ) ) ) 

What I want is for it to come out like this;

  ["YOLANDA MEJIA ROJAS","IRMA VARA SANCHEZ","DIANA AGUAYO MORENO"]
    
asked by Ivan More Flores 11.05.2017 в 20:19
source

2 answers

1

It is not necessary to iterate with a for, simply use array_columns and it returns all the values

<?php

$tra = new area();
$madres = $_POST['mesa'];
$reg = $tra->traer_area($madres);
if (count($reg) == 0) {
    $data  = [];
} else {
   $data =array_columns($reg, 'nombre_completo');
}
print_r($data);
?>
    
answered by 11.05.2017 в 20:36
0

The problem:

When iterating the array $reg , in the variable $data['data'] :
- You are stepping on your value in each loop instead of adding a value.
- You are always assigning the complete $reg fix, instead of a specific value of it.
When printing the $data fix, you are not indicating the data position.

Solution:

  • Optional : You could iterate the array returned by $tra->traer_area using foreach to simplify your code.
  • Add the $data['data'] fix using the $data['data'][] syntax.
  • Indicate that you want to add a specific value of the data record to the $data array.
  • Call print_r on $data['data'] to get the desired result.

So for example:     

$tra = new area();
$madres = $_POST['mesa'];
$regs = $tra->traer_area($madres);
$data['data'] = array();
foreach($regs as $reg) {
    $data['data'][] = $reg['nombre_completo'];
}
print_r($data['data']);
?>

Demo

    
answered by 11.05.2017 в 20:32