How to insert index and element into an array

4

I am developing a loop to compare two tables in a database. The intention is to know how many people were indicated by a same employee of the company. For this, I need to start an array as follows:

foreach($linhas as $linha){
  $varivael = array( $linha['nome'] => 0);
 };

The problem is that this only adds the last item in the table, and I want them all to be inserted, which looks like this:

$varivael = array( $linha['nome'] => 0, $linha['nome'] => 0, $linha['nome'] => 0, ...);

I thought about using array_push (), but it only inserts the element, not the index.

How to proceed?

    
asked by anonymous 04.05.2017 / 17:16

3 answers

1

Just closing the question. The answer was given by @ Anderson, where you should change the line $varivael = array( $linha['nome'] => 0); to $varivael[$linha['nome']] = 0 .

    
04.05.2017 / 19:24
6

If you just need to create a new array, indicate this in the assignment. The way you are in the question at every turn of the foreach the value of $variavel is overwritten. To accumulate the items in the array, $varivael[] = 'valor';

Change:

foreach($linhas as $linha){
  $varivael = array( $linha['nome'] => 0);
}

To:

foreach($linhas as $linha){
  $varivael[] =  $linha['nome'];
}
Another alternative approach is to use array_map() to return an array with all values of nome and call array_fill_key() to create a new array where the keys are the names and default value for all is zero in the case.

array_map() can be changed by array_column() if you use version 5.5 or higher of php.

$arr = array(array('nome' => 'fulano'), array('nome' => 'beltrano'), array('nome' => 'doge') );
$chaves = array_map(function($item){ return $item['nome']; }, $arr);
$novo = array_fill_keys($chaves, 0);
print_r($novo);

Example array_map - ideone

$arr = array(array('nome' => 'fulano'), array('nome' => 'beltrano'), array('nome' => 'doge') );
$chaves = array_column($arr, 'nome');
$novo = array_fill_keys($chaves, 0);
print_r($novo);

Example array_column - ideone

    
04.05.2017 / 18:00
-1

Hello, with me it worked using:

$variavel[$linha]['nome'] = 0
    
26.07.2018 / 18:51