Dizi uzunluğu incakephp bulma

1 Cevap php

Benim cakePHP denetleyicisi saveReport() adında burada $attribute_ids Ajax yazılan elde edilen tüm seçilmiş nitelikleri tutan bir dizidir .. bir eylem var

function saveReport()
{
    echo $this->params['form']['formid'];
    echo $this->params['form']['reportTitle'];
    echo $this->params['form']['attr'];
    $attribute_ids=$this->params['form']['attr'];
    $comma_separated = explode(",", $attribute_ids);

    for($i=0;$i<15;$i++)
    {
        echo $comma_separated[$i]; 
        echo "     ";

        $this->data['Report']['title']=$this->params['form']['reportTitle'];
        $this->data['Report']['form_id']=$this->params['form']['formid'];
        $this->data['Report']['attr_id']=$comma_separated[$i]; 
        $this->Report->saveAll($this->data);
    }
}

$comma_separated 's i döngü için şimdi ben varsayılan olarak 15 olarak kullanmış bu kullanın böylece $comma_separated bir dizi uzunluğunu belirlemek için nasıl ...

1 Cevap

$comma_separated bir dizi ise, count içerdiği kaç unsurları öğrenmek için kullanabilirsiniz.

Örneğin, eğer dizi bu içerir:

$comma_separated[0] = 'glop';
$comma_separated[1] = 'hello';
$comma_separated[2] = 'world';

Sen kullanabilirsiniz:

$result = count($comma_separated);
var_dump($result);

Ve alacak:

int 3


You could also use foreach to iterate over the elements of your array, instead of for ; this way, you won't need to know how many elements it contains.

Örneğin:

foreach ($comma_separated as $element) {
    var_dump($element);
}

Alacak:

string 'glop' (length=4)
string 'hello' (length=5)
string 'world' (length=5)