gpt4 book ai didi

php - 如何获取自定义元数据

转载 作者:行者123 更新时间:2023-12-04 13:38:46 24 4
gpt4 key购买 nike

我希望有人能提供帮助,我一直在尝试从 Woocommerce 上的自定义字段插件中获取信息(与 WooCommerce 订阅一起使用)。

我正在 try catch 详细信息,以便我可以将其 JSON POST 到另一个平台。

我已经成功地连接到订阅的事件状态,通过 $subscription 变量获取详细信息,JSON 对其进行解码,然后捕获我在 'meta_data' 数组中找到的自定义字段部分。

现在将其保存到名为 $orderdata 的变量中。

变量看起来像

array (
0 =>
array (
'id' => 20992,
'key' => '_billing_parent_first_name',
'value' => 'Father First Name',
),
1 =>
array (
'id' => 20993,
'key' => '_billing_parent_last_name',
'value' => 'Father Last Name',
),
2 =>
array (
'id' => 20994,
'key' => '_billing_parent_email',
'value' => 'father@test.com',
),
3 =>
array (
'id' => 20995,
'key' => '_billing_parent_number',
'value' => '12345678',
),
4 =>
array (
'id' => 20996,
'key' => '_billing_childs_first_name',
'value' => 'test',
),
5 =>
array (
'id' => 20997,
'key' => '_billing_childs_last_name',
'value' => 'test',
),
6 =>
array (
'id' => 20998,
'key' => '_billing_childs_email',
'value' => 'test@gmail.com',
),
7 =>
array (
'id' => 20999,
'key' => 'is_vat_exempt',
'value' => 'no',
),
8 =>
array (
'id' => 21000,
'key' => 'thwcfe_ship_to_billing',
'value' => '1',
),
)

我的目标是将像 _billing_parent_number 这样的每个字段保存到一个变量中,以便我可以使用 POST 将其发送出去。

有谁知道我可以捕获我需要的字段的方法吗?

我尝试了多种方法,从数组搜索到数组列(我使用 error_log 在 Wordpress 中进行测试,以便我可以看到结果)。

我接近 foreach 循环,但我不知道如何在对象中获取以下字段并获取它的值,在这种情况下 next() 不起作用:(

任何帮助表示赞赏!
add_action( 'woocommerce_subscription_status_active', 'get_details_add_bundle' );

function get_details_add_bundle($subscription) {

$obj = json_decode($subscription, true);

error_log($obj);

$orderData = $obj['meta_data'];

foreach($orderData as $key => $value) {
if($key == 'key' && $value="_billing_childs_email"){
error_log(next($orderData)[2]);
}

}

最佳答案

我想你可能会认为这对键和值等来说有点太多了。您发布的数组是一个数组数组。这意味着您可以通过 foreach 运行它。循环,并且需要一个子循环(或其他方法)来访问键和值 - 但你甚至不需要走那么远。

如果我们创建一个新数组(您最终将发布,所以我假设您只需要 key => value 对),我们可以将子数组中的值插入其中,因为它们是一维的,这非常容易!

$postable = array(); // Create a new array (we'll eventually POST this)

// get each sub array, one at a time
foreach( $orderdata as $data ){
/* The $postable "key" will be the value of $data['key'], and the value
pair for it will be the value of $data['value'] */
$postable[$data['key']] = $data['value'];
}

现在我们已经将这些对中的每一个都插入了 $postable数组,我们最终得到一个简单的 key => value配对关联数组:
array(#) {
["_billing_parent_first_name"] => string(17) "Father First Name"
["_billing_parent_last_name"] => string(16) "Father Last Name"
["_billing_parent_email"] => string(15) "father@test.com"
/* … */
}

这是一个工作示例(为简洁起见,使用截断数组): https://3v4l.org/kWQnB

关于php - 如何获取自定义元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60213339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com