Store value and quantity PHP array

3

I need to scan the first array and store the value and amount of that value in another array . I'm not getting it because I'm having difficulty 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 value and quantity 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"
  }
}
    
asked by anonymous 09.11.2016 / 12:36

3 answers

2

Hi, Kevin

I believe you can resolve this by using the array_count_values() function. Documentation here .

At the end of the use of this function, its values will become keys of the other array. With foreach ($array as $valor => $ocorrencias) you can traverse the produced array and put it in the desired format. ;)

    
09.11.2016 / 12:45
3

In order to complement the response of Macário Martins, 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 array_count_values()

$resultado = array_count_values($dados_unidimensional);

And $ result will be something like

["12" => 2, "13" => 2, "100" => 1]
    
09.11.2016 / 13:36
0

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

<?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 [] switch to your arrays

    
09.11.2016 / 12:48