php

时间:2015-11-05 06:21:34

标签: php arrays count

我有以下stdClass Object结构数组,并且需要计数数量。收到Std类作为来自第三方API的响应,因此它是动态的。

stdClass Object
    (
        [Offer] => Array
            (
                [0] => stdClass Object
                    (
                        [Offerid] => 1
                        [LoanAmount] => 2****
                        [InterestRate] => 2*
                        [Term] => 36
                        [MonthlyPayment] => 7***
                        [Annualfee] => 0
                        [OriginationFee] => 1***

                    )

                [1] => stdClass Object
                    (
                        [Offerid] => 1
                        [LoanAmount] => 2****
                        [InterestRate] => 2*
                        [Term] => 36
                        [MonthlyPayment] => 7***
                        [Annualfee] => 0
                        [OriginationFee] => 1***
                    )

                [2] => stdClass Object
                    (
                        [Offerid] => 1
                        [LoanAmount] => 2****
                        [InterestRate] => 2*
                        [Term] => 36
                        [MonthlyPayment] => 7***
                        [Annualfee] => 0
                        [OriginationFee] => 1***
                    )

            )

    )

我想在 [优惠] 中计算数组的数量,因为我已经完成了以下操作:

echo "count----------".count($offers);

但它会将 1 作为计数 count----------1 在这种情况下,count是 3 ,我想要3作为输出。 请建议。 我也用过这个        echo" count ----------" .count((array)$ offers); 这也行不通。

4 个答案:

答案 0 :(得分:1)

你可以像转换" stdClass对象"进入正常数组并在该计数后尝试($ offer);

只需写入(数组)$ object;它将转换为普通数组

答案 1 :(得分:0)

伯爵应该工作。

<?php
$obj = new stdClass();
$obj->Offer = array(
    array('Offerid' => 1, 'LoanAmount' => '2***', 'InterestRate' => '2*', 'Term' => 36, 'MonthlyPayment' => '7***', 'Annualfee' => 0, 'OriginationFee' => '1***'),
    array('Offerid' => 1, 'LoanAmount' => '2***', 'InterestRate' => '2*', 'Term' => 36, 'MonthlyPayment' => '7***', 'Annualfee' => 0, 'OriginationFee' => '1***'),
    array('Offerid' => 1, 'LoanAmount' => '2***', 'InterestRate' => '2*', 'Term' => 36, 'MonthlyPayment' => '7***', 'Annualfee' => 0, 'OriginationFee' => '1***'),
);
echo count($obj->Offer); // Outputs 3
?>

Live example

答案 2 :(得分:0)

我已按照以下方式解决了我的问题:

foreach ($offers as $key=> $value) 
{
   echo "<br/>count->".count($value);
}

这只循环一次,并给我结果。

答案 3 :(得分:0)

试试这个:

<?php
class Example {
    public $public = 'prop:public';
    private $prv   = 'prop:private';
    protected $prt = 'prop:protected';
}

$arrayobj = new ArrayObject(new Example());
var_dump($arrayobj->count());

$arrayobj = new ArrayObject(array('first','second','third'));
var_dump($arrayobj->count());
?>

以上示例将输出:

int(1)
int(3)

Answer Source