How to insert index and element within an array

Asked

Viewed 6,177 times

4

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

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

The problem is that this way only adds the last item of the table, and I want them all inserted, which is as follows:

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

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

How to proceed?

  • 3

    Within the foreach try to do $varivael[$linha['nome']] = 0.

  • Apparently it worked. Although I’ve done it again, for some reason, this one right. Thank you.

2 answers

8

If you only need to create a new array, enter this in the assignment. As in the question at each foreach turn the value of $variavel is overwritten. To accumulate items in the array simply $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 default names and value for everyone is zero in the case.

the array_map() can be exchanged for array_column() if you use php version 5.5 or higher.

$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

  • But this doesn’t fix it. I need to define both the value and key of it, so that the key is $line['name'] and the value is an integer number that can be added further forward.

  • @Rafaelpessoa the name repeats itself?

  • Colleague @Anderson solved it. Strangely he said to do something I had already done, but this time solved it. Thanks for the help

1


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.