计算数组中元素的数量

时间:2014-08-28 18:15:50

标签: php

我的数据库中有这个:3,14,12,13

被叫$ user ['buddylist']

这是我的代码,但输出是1而不是4,出了什么问题?

$prefix = '"';
$tag = explode( ',', $user['buddylist'] );
$foll = $prefix . implode( '",' . $prefix, $tag ) . '",';
$following = array($foll );
$nr = count($following);

$ foll的输出是“3”,“14”,“12”,“13”,:/ / / p>

1 个答案:

答案 0 :(得分:2)

因为当你这样做时,foll是一个字符串:

$foll = $prefix . implode( '",' . $prefix, $tag ) . '",';

执行此操作时,您正在创建一个包含一个元素的数组:

$following = array($foll );

如果要计算,则需要在将数组转换为字符串之前对其进行计数:

$prefix = '"';
$tag = explode( ',', $user['buddylist'] );
$nr = count($tag);
$foll = $prefix . implode( '",' . $prefix, $tag ) . '",';
$following = array($foll );

我可能会这样编码:

class Buddies {
     private $buddies;
     public function __construct($buddy_list_string) {
         $this->buddies = explode( ',', $buddy_list_string);
     }
     public function count() {
         return count($this->buddies);
     }
     public function __toString() {
         return '"' . implode('","', $this->buddies) . '"';
     }
     public function toArray() {
         return $this->buddies;
     }
}

$buddies = new Buddies($user['buddylist']);
echo $buddies->count(); //4
echo $buddies; //"3","14","12","13"
foreach($buddies->toArray() as $buddy) {
     //do stuff
}