Last active
October 14, 2021 21:05
-
-
Save wpscholar/8360746 to your computer and use it in GitHub Desktop.
Get a value from an object or an array. Allows the ability to fetch a nested value from a heterogeneous multidimensional collection using dot notation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get a value from an object or an array. Allows the ability to fetch a nested value from a | |
* heterogeneous multidimensional collection using dot notation. | |
* | |
* @param array|object $data | |
* @param string $key | |
* @param mixed $default | |
* @return mixed | |
*/ | |
function get_value( $data, $key, $default = null ) { | |
$value = $default; | |
if ( is_array( $data ) && array_key_exists( $key, $data ) ) { | |
$value = $data[$key]; | |
} else if ( is_object( $data ) && property_exists( $data, $key ) ) { | |
$value = $data->$key; | |
} else { | |
$segments = explode( '.', $key ); | |
foreach ( $segments as $segment ) { | |
if ( is_array( $data ) && array_key_exists( $segment, $data ) ) { | |
$value = $data = $data[$segment]; | |
} else if ( is_object( $data ) && property_exists( $data, $segment ) ) { | |
$value = $data = $data->$segment; | |
} else { | |
$value = $default; | |
break; | |
} | |
} | |
} | |
return $value; | |
} |
<?php
$json = '{ "full_details_acknowledgement": "10", "offer_letter_acknowledgement": "10", "offer_letter": "10", "offer_letter_variables": [ "basic_salary", "housing_allowance", "transport_allowance", "meal", "entertainment", "hazard_allowance", "leave_allowance", "utility", "monthly_gross_salary", "statutory_deductions", "employee_pension", "payee_tax", "total_deductions", "net_monthly_salary", "austin" ], "company": "global-manpower" }';
$data = json_decode( $json );
get_value( $data, 'offer_letter_variables', [] );
The third parameter just sets the default value to be an empty array, since that is what is expected to be returned.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what of in this senerio
{ "full_details_acknowledgement": "10", "offer_letter_acknowledgement": "10", "offer_letter": "10", "offer_letter_variables": [ "basic_salary", "housing_allowance", "transport_allowance", "meal", "entertainment", "hazard_allowance", "leave_allowance", "utility", "monthly_gross_salary", "statutory_deductions", "employee_pension", "payee_tax", "total_deductions", "net_monthly_salary", "austin" ], "company": "global-manpower" }
and we want to access offer_letter_variables