2012-12-12 55 views
1

我的PHP脚本计数阵列array_count_values

$file_carrito=file("carrito.dat"); 

    $x=0; 

    for($i=0;$i<sizeof($file_carrito);$i++) 
    { 
    $array_products_1[]=$file_carrito[$i]; 

    $x++; 
    } 



echo (array_count_values($array_products_1)); 

在这个简单的文件中的.dat,存储所有产品的用户添加,并且在每种情况下总的产品每个ID和案例

例如数我可以将一个产品的5个ID和其他产品ID的其他4个产品进行归档,最后,这必须将具有相同ID的产品存储到数据文件中

例如:5支铅笔,3把椅子,2张桌子,等.....

The problem it´s no works : echo (array_count_values($array_productos_1)); 



content of carrito.dat : 

p1 
p1 
p1 
p3 
p3 
p3 
p2 
p2 
p2 
p1 
p1 



With this function of array i want get : 

Product p1 ---- (5) 
Product p2 ----- (3) , etc 

Thank's

+0

你应该表现出什么'carrito.dat'看起来像 – Sharlike

+0

什么*它做到了吗? “不起作用”不是问题描述。 – deceze

+0

使用会话[本地或服务器]比依赖文件更好。 – moonwave99

回答

0

算你的价值观这样

$array = array('x', 'x', 'x', 'x', 'y', 'y'); 
$counts = array(); 
foreach($array as $value) { 
    $counts[$value] = array_key_exists($value, $counts) ? $counts[$value]+1 : 1; 
} 

print_r($counts); 
你的情况

。该阵列填充

$array = explode("\n", file_get_contents(...)); 
+0

是的,但我需要得到正常值,没有在这种形式,没有使用print_r ..... thank's – user1860536

0

最简单的办法:

$data = file('carrito.dat'); 

print_r(array_count_values($data)); 

它会显示类似下面:

Array 
(
    [p1] => 5 
    [p3] => 3 
    [p2] => 3 
) 
+0

是的,但我需要得到正常值,否在这种形式,谢谢 – user1860536

+0

$ data = file ( 'carrito.dat'); $ products = array_count_values($ data); foreach($ product as $ key => $ value){echo“Product $ key ---- $ value
”; } – AlecTMH