Organize array

Asked

Viewed 233 times

0

Good how I can organize this array without using a loop

Original array

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

Desired array

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

ok I understood what you mean... I had done in loop even more I ended up changing by the of the answer I will go back to the loop that is easier to understand. Now it turned out that there was an optimization, because I took the code and adapted it to another part that was making 2 queries in mysql, getting like this

      $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 making 2 queries one for product and another for category, there is not as I put together that 2 reduce at once not? or n the need since I avoided a search in mysql

NOTE ah and a detail, I wrote the loop on the ideone site and realized that with the loop, the response time was equal 2ms, more with the loop the weight was about 600kb lower

Is there any way to improve this logic? what’s going on and what I’m doing 2 loop to organize the final answer, and it’s 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];
  • Set "organize". You can’t tell what you want. Even more with tag optimization. And what is the goal? The array is exactly this?

  • What you want has no logic; see, in the original array, the Arrows of the input element indicates that that value will be defined for that element. In the intended array you are separating the elements, then the second reading would be: array(0){ with elements 0.1 with the values "input" and "4" }.

  • @Maniero yes array and that, but the information and mutable can have more indexes or less

  • It’s impossible to do without one loop, What you can do is use an abstraction that hides it. Honestly, this is not optimization, it’s the other way around. It may make it shorter, but often less readable. Actually in this case I make shorter with the loop, and with more performance, so it is of those requirements that does not make the slightest sense.

  • @Maniero blz understood, now I edited the post ended that this answer helped me with another problem that I was not liking very much as it was, if you have like a look and see if it needs modification

1 answer

0


Personally I advise you to use the loop really normal 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 it has direct and exact functions for the result that prentede, 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 keys of the original array by generating a new entry for each key. To fetch the value associated with the key use 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;
});

Which 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)
  }
}

See this result in Ideone

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

Loop normal

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

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

Not only is it much simpler, but it’s more performing.

Completion

Use only the native functions for what makes sense. The transformation itself that you are doing does not seem to make much sense, as it ends up having exactly the same information but with more depth, another level in the array. And even in a foreach normal can access information in both versions.

  • blz gave an update on the doubt, as it came to a conclusion

  • @Willian The code that showed now in the question is not very clear to me its objective, but I say already advance that is probably not the best idea. What use do you want to give ? Do you want to save one array for the names and another for the categories? Aside from the "performance" problem, it probably comes from the fact that you’re doing two queries that you can probably do in one.

  • correct just that I used a loop, I was half tired or I saw that it was the same idea of the loop more anyway thank you, yes it ended up that I reduced a query in the bank, thank you, ah and the best way to do this is to just do a search and save in the array and work that array so it will always arrive at the info you need?

  • @Willian Yes that’s it, store in the array everything you need and then use it from there. But to store in the array you only need 1 loop.

  • ready clarified the doubts now I only have one more about optimization

Browser other questions tagged

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