Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

php - Search meta key in object and get value

I did a var_dump of my current order in Woocommerce. The output is a big object of data: https://snippi.com/s/rftgioq

Somewhere in this object is the key _enviso_order_id and _enviso_order_number. Is it somehow possible to do a "search" in the object and get the corresponding values.

$order = wc_get_order( $order_id ); // this gets the data from the current order
var_dump($order); // dump from the data. Full example: https://snippi.com/s/rftgioq

I've tried this to get the _enviso_order_id

$enviso_id = $order->_enviso_order_id;
echo $enviso_id;

But it's empty.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After discussing the issue with OP (which can be found here), the following answered the question:

$value = $order->get_meta_data()[8]->get_data()['value'];
$metadata = json_decode($value);
$enviso_id = $metadata[0]->_enviso_order_id;

echo $enviso_id;

The issue with this is that the 'enviso' metadata may not always be stored in the 8th element of the array, which will produce errors if using the code sample above.

The array returned from get_data() also includes a key called key, which indicates what the metadata relates to (in this case its '_enviso_order_info'), we can use this to create a helper function to extract the 'enviso' metadata from the order:

function get_enviso_metadata($order) {
    $metadatas = $order->get_meta_data();
    
    foreach($metadatas as $metadata) {
        $data = $metadata->get_data();
        
        if($data['key'] == '_enviso_order_info') {
            return json_decode($data['value'], true)[0];
        }
    }
    
    return [];
}

Usage example:

$order = wc_get_order($order_id);
$envisoMetadata = get_enviso_metadata($order);

echo $envisoMetadata['_enviso_order_id'];

As I don't have access to the development environment I have no way of testing this, but after discussing it with OP, I think it should work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...