从PHP中的函数返回的数组中回显键值
对不起,如果这是一个有点noob的问题,我仍然是一个php初学者 我需要从函数返回的数组中回显国家密钥。 我尝试了各种方法试图从数组中获得我想要的值,但每次都没有得到我想要的结果 我想将返回数组中的“country”值设置为变量,以便对该值执行if参数。请帮忙 下面是我尝试做的示例-从PHP中的函数返回的数组中回显键值,php,arrays,function,Php,Arrays,Function,对不起,如果这是一个有点noob的问题,我仍然是一个php初学者 我需要从函数返回的数组中回显国家密钥。 我尝试了各种方法试图从数组中获得我想要的值,但每次都没有得到我想要的结果 我想将返回数组中的“country”值设置为变量,以便对该值执行if参数。请帮忙 下面是我尝试做的示例- <?php $country = get_shipping_address()['country'] if ( $country=="GB" ) { do this; } ?> 您的问题是,
<?php
$country = get_shipping_address()['country']
if ( $country=="GB" ) {
do this;
}
?>
您的问题是,您在您的功能中正在这样做:
foreach ( $address as $part ) {
if ( ! empty( $part ) ) {
$joined_address[] = $part;
}
}
$this->shipping_address = implode( ', ', $joined_address );
这样做的目的是用数组中的所有值生成一个字符串。例如:
derp, derp, derp, derp, derp, derp
您需要返回$address变量
return $address;
使您的函数如下所示:
function get_shipping_address() {
$address = array();
if (!$this->shipping_address) {
if ($this->shipping_address_1) {
// Formatted Addresses
$address = array(
'address_1' => $this->shipping_address_1,
'address_2' => $this->shipping_address_2,
'city' => $this->shipping_city,
'state' => $this->shipping_state,
'postcode' => $this->shipping_postcode,
'country' => $this->shipping_country
);
}
}
return $address;
}
感谢Darren(以及所有发表评论的人)
这就成功了
我创建了一个新函数,并将其更改为只返回我需要的值,因为我只需要知道国家值。
因此,我们对函数进行了如下更改。
谢谢你的帮助
function get_my_shipping_address() {
if ( ! $this->shipping_address ) {
if ( $this->shipping_address_1 ) {
// Formatted Addresses
$address = array(
'address_1' => $this->shipping_address_1,
'address_2' => $this->shipping_address_2,
'city' => $this->shipping_city,
'state' => $this->shipping_state,
'postcode' => $this->shipping_postcode,
'country' => $this->shipping_country
);
}
}
return $address['country'];
}
您没有返回数组,而是返回字符串$this->shipping\u address=内爆(“,”,$joined\u address)当的
条件评估为false时,code>不会是$address
未定义的?@Verhaeren它会的,但是除非OP可以指定任何需要覆盖该方面的内容,否则这个答案涵盖了他的范围:)或者address
可以在函数启动后立即有一个默认值。完成,并且它有一个默认的空数组。很好,但是,当他尝试像这样检查返回的数组时,他也会得到一个未定义索引错误get\u shipping\u address()['country']
。
function get_my_shipping_address() {
if ( ! $this->shipping_address ) {
if ( $this->shipping_address_1 ) {
// Formatted Addresses
$address = array(
'address_1' => $this->shipping_address_1,
'address_2' => $this->shipping_address_2,
'city' => $this->shipping_city,
'state' => $this->shipping_state,
'postcode' => $this->shipping_postcode,
'country' => $this->shipping_country
);
}
}
return $address['country'];
}