很抱歉,如果这是一个noob问题,我仍然是php的初学者....
我需要从函数返回的数组中回显Country键。 我尝试过尝试从数组中获取值的各种方法,但每次都没有得到我想要的结果。
我想将返回数组中的'country'值设置为变量,以便对值执行if参数。请帮忙......
我试图在下面做的样本 -
<?php
$country = get_shipping_address()['country']
if ( $country=="GB" ) {
do this;
}
?>
以下是功能 -
function get_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
);
$joined_address = array();
foreach ( $address as $part ) {
if ( ! empty( $part ) ) {
$joined_address[] = $part;
}
}
$this->shipping_address = implode( ', ', $joined_address );
}
}
return $this->shipping_address;
}
答案 0 :(得分:2)
您的问题是您在自己的功能中执行此操作:
foreach ( $address as $part ) {
if ( ! empty( $part ) ) {
$joined_address[] = $part;
}
}
$this->shipping_address = implode( ', ', $joined_address );
这样做会使string
包含数组的所有值。例如:
derp, derp, derp, derp, derp, derp
您想要的是返回$address variable
。
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;
}
答案 1 :(得分:0)
感谢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'];
}