Store PHP array value and quantity

Asked

Viewed 130 times

3

I need to sweep the first array and store the value and quantity of that value in another array. I’m not succeeding because I’m having trouble storing the values in another array.

Array:

array(5) {
  [0]=>
  array(1) {
    [0]=>
    string(2) "12"
  }
  [1]=>
  array(1) {
    [0]=>
    string(2) "13"
  }
  [2]=>
  array(1) {
    [0]=>
    string(3) "100"
  }
  [3]=>
  array(1) {
    [0]=>
    string(3) "12"
  }
  [4]=>
  array(1) {
    [0]=>
    string(3) "13"
  }
}

Array with the amount and value I need:

array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(2) "12"
    int() "2"
  }
  [1]=>
  array(1) {
    [0]=>
    string(2) "13"
    int() "2"
  }
  [2]=>
  array(1) {
    [0]=>
    string(3) "100"
    int() "1"
  }
}
  • Do you want to count the amount of items in the array? The count() does not produce results?

  • It brings yes only I can not store in another array, I would like a new array that nor mentioned above. Not only one count showing the amount of items in the array.

3 answers

2

To complement Macário Martins' response, you would first have to transform the multidimensional array into a simple array... I used the OS example

$dados_unidimensional = call_user_func_array('array_merge', $dados_bidimensional);

this will transform your array

[ [ "12" ], [ "13" ], [ "100" ], [ "12" ], [ "13" ] ]

in

[ "12", "13", "100", "12", "13" ]

With this you can use the array_count_values()

$resultado = array_count_values($dados_unidimensional);

And $result will be something like

["12" => 2, "13" => 2, "100" => 1]

2


Hi, Kevin

I believe you can solve this issue using the function array_count_values(). Documentation here.

After using this function, its values will become keys of the other array. With one foreach ($array as $valor => $ocorrencias) you can go through the produced array and put it in the desired format. ;)

0

Your array seems to be a multi-dimensional. Try it this way:

<?php

$ar1[] = array("red","green","yellow","blue");
$ar1[] = array("green","yellow","brown","red","white","yellow");
$ar1[] = array("red","green","brown","blue","black","yellow");

$res = array_icount_values ($ar1);
print_r($res);

function array_icount_values($arr,$lower=true) {
     $arr2=array();
     if(!is_array($arr['0'])){$arr=array($arr);}
     foreach($arr as $k=> $v){
      foreach($v as $v2){
      if($lower==true) {$v2=strtolower($v2);}
      if(!isset($arr2[$v2])){
          $arr2[$v2]=1;
      }else{
           $arr2[$v2]++;
           }
    }
    }
    return $arr2;
} 

In $ar1[] trade for your arrays

Browser other questions tagged

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