开发者

PHP Function -> Array

I have a PHP function which populates a multi-dimensional array

$client->getResponse()
开发者_如何学JAVA

I want to utilise that array directly, something like this:

echo '$client->getResponse()[0]'; which obviously doesn't work.

I don't want to have to do this

$arr = array($client->getResponse()); as that brings in another level of array which I don't really want.


$arr = $client->getResponse();
echo $arr[0];

should suffice.

You can display every item inside the array with a foreach

foreach($client->getResponse() as $clientResponse){
    echo $clientResponse;
}


What about introducing a tmp?

$tmp = $client->getResponse();
echo $tmp[0];


Attention, if you use:

foreach($client->getResponse() ...)

The function ''getResponse'' will be execute in each iteration... If the data change during the "each" process, you may have incoherent values. No ?


Can't you create another method for the class that $client represents? maybe "GetResponseEntry($id)", like so:

function getResponseEntry( $id, $default = null )
{
    static $response = null;

    if( $response === null )
        $response = $this->getResponse();

    if( isset($response[$id]) )
        return $response[$id];
    else
        return $default;
}

Then you could call it like so:

echo $client->getResponseEntry(0);

It may not be suitable for all circumstances, but ... maybe, just maybe, it'll work here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜