Skip to content
PHP Logo

How can you efficiently extract specific values from a complex JSON array in PHP?

When dealing with a complex JSON array in PHP, you can efficiently extract specific values by decoding the JSON string into an associative array using `json_decode()`. Once you have the array, you can access the specific values using array keys or by iterating through the array. Additionally, you can use functions like `array_column()` or `array_filter()` to extract specific values based on certain criteria.

php
// Sample JSON string
$jsonString = '{
    "users": [
        {
            "id": 1,
            "name": "John Doe",
            "email": "john@example.com"
        },
        {
            "id": 2,
            "name": "Jane Smith",
            "email": "jane@example.com"
        }
    ]
}';

// Decode JSON string into an associative array
$data = json_decode($jsonString, true);

// Extract specific values
$userIds = array_column($data['users'], 'id');
$userNames = array_column($data['users'], 'name');

// Print extracted values
print_r($userIds);
print_r($userNames);