Arrange array

0

Good how can I organize this array without using a loop

Original Array

["Entrada" => 4, "Prato principal" => 1]

Intended Array

[["Entrada",4],["Prato principal",1]]

Ok I understood what you guys mean ... I had looped even more so I ended up changing by the answer I'm going back to the loop that's easier to understand. Now it turned out that an optimization even happened, because I took the code and adapted it to another part that was doing 2 queries in mysql, thus

      $stmt = getConn()->query("SELECT hash,nome,categoria FROM produto");
      $qryProduto = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
      $qryProdNome = array_reduce(array_keys($qryProduto), function($novo, $chave) use ($qryProduto){
        $novo[$chave] = $qryProduto[$chave][0]['nome'];
      return $novo;
      });
      $qryProdCateg = array_reduce(array_keys($qryProduto), function($novo, $chave) use ($qryProduto){
        $novo[$chave] = $qryProduto[$chave][0]['categoria'];
      return $novo;
      });
      /*$stmt = getConn()->query("SELECT hash,categoria FROM produto");
      $qryProdCateg = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
      $qryProdCateg = array_map('reset', $qryProdCateg);
      $qryProdCateg = array_map('reset', $qryProdCateg);*/

I was doing 2 queries one for product and another for category, there is no way I add that 2 reduces at once no? or no need since I avoided a search in mysql

NOTE ah and a detail, I wrote the loop in the ideone website and realized that with the loop, the response time was equal to 2ms, plus with the loop the weight was about 600kb smaller

Can you improve this logic? what is catching and what I'm doing 2 loop to organize the final answer, and this is bothering me

$stmt = getConn()->query("SELECT id,unix_timestamp(data) AS data FROM loginclient");
  $qryLoginClient = $stmt->fetchAll();
  $totaluser = $stmt->rowCount();
  $onoff = ( $totaluser > 0 ? true : false ); // preparação para lazzyload
  $usuarioHj = 0;
  $usuarioOntem = 0;
  $bugfix = 0;
  $org_user = [];
  foreach($qryLoginClient as $data){
    if(strtotime($vhoje) <= $data['data']):
      $usuarioHj++;
    elseif(strtotime($vontem) <= $data['data']):
      $usuarioOntem++;
    endif;
    $maskdate = date("d-m-Y", $data['data'] );
    if($bugfix <= 15):
      ( !isset($org_user[$maskdate]) ? $org_user[$maskdate] = 1 : $org_user[$maskdate]++ );
    endif;
    $bugfix++;
  }
  foreach($org_user as $item => $id){
    unset($org_user[$item]);
    $org_user[] = [$item,$id];
  }
  $bugfix = ( $usuarioOntem == 0 ? 1 : $usuarioOntem );
  $taxa_crescimento = ceil(($usuarioHj-$usuarioOntem)/$bugfix*100);
  $respNovoUsuario = [$totaluser,$taxa_crescimento,$org_user];
    
asked by anonymous 17.06.2018 / 09:09

1 answer

0

I personally advise you to use the same loop and do what you have to do that is simpler to read, generating a less complex solution. There are many other scenarios that would be advisable to do with native functions because they have direct and accurate functions for the result you create, which is not the case.

Get a solution with native functions using for example array_reduce and array_keys . The idea is to "reduce" the original array's keys by generating a new entry for each key. To get the value associated with the key uses the original array.

Example:

$arr = ["Entrada" => 4, "Prato principal" => 1];

$res = array_reduce(array_keys($arr), function($novoArr, $chave) use ($arr){
    $novoArr[] = Array($chave, $arr[$chave]);
    return $novoArr;
});

That gives you the following result:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(7) "Entrada"
    [1]=>
    int(4)
  }
  [1]=>
  array(2) {
    [0]=>
    string(15) "Prato principal"
    [1]=>
    int(1)
  }
}

View this result on Ideone

Note that I had to use ($arr) to access the original array within callback passed to array_reduce .

With normal loop

Now compare the previous solution to one using a normal loop :

$res = Array();
foreach($arr as $key => $val){
    $res[] = Array($key, $val); 
}

Not only is it much simpler, but more perfomous.

Conclusion

Use only the native functions for what makes sense. The very transformation you are making does not seem to make much sense, as you end up with exactly the same information but with more depth, one more level in the array. And even in a foreach normal you can access the information in both versions.

    
17.06.2018 / 14:18