News

Handle Nested Data Structures in PHP with the Data Block Package

Published
Handle Nested Data Structures in PHP with the Data Block Package image

The Data Block package for PHP can handle querying, filtering, and setting nested data structures. This package offers a streamlined approach to handling nested data and complex JSON structures. You can create a Block object in multiple ways, such as a JSON file, an array, or a URL, for example:

use HiFolks\DataType\Block;
use HiFolks\DataType\Enums\Operator;

Block::fromJsonUrl('https://api.github.com/orgs/hi-folks/repos')
    ->select('full_name', 'stargazers_count')
    ->where('stargazers_count', Operator::GREATER_THAN, 0)
    ->orderBy('stargazers_count', 'desc')
    ->forEach(
        function ($item) {
            echo $item->get('full_name').' : ';
            echo $item->get('stargazers_count').PHP_EOL;
        }
    );

Apart from the many methods to conditionally get data, filter and order data, you can also get and set nested data, extract keys, and many other operations you would expect from working with complex data:

use HiFolks\DataType\Block;

$fruits = [
    "avocado" =>
    [
        'name' => 'Avocado',
        'fruit' => '🥑',
        'wikipedia' => 'https://en.wikipedia.org/wiki/Avocado',
        'color'=>'green',
        'rating' => 8
    ],
    // ...
];

$data = Block::make($fruitsArray);

$data->get('avocado'); // returns an array
$data->get('avocado.color'); // returns the string "green"

$data->set('cherry', [
    'name' => 'Cherry',
    'fruit' => '🍒',
    'wikipedia' => 'https://en.wikipedia.org/wiki/Cherry',
    'color' => 'red',
    'rating' => 9,
]);

$data->set('cherry.rating', 5);

Besides working with data using the Block object, you can also export it to various formats such as a JSON string, JSON file, or YAML. This package is documented well in the GitHub README file.

🧑‍💻 You can get started with this package on GitHub: Hi-Folks/data-block

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Laravel FFmpeg 9: Encode Video and Stream HLS and DASH image

Laravel FFmpeg 9: Encode Video and Stream HLS and DASH

Read article
Migration Durations and Job Memory Usage in Laravel 13.45 image

Migration Durations and Job Memory Usage in Laravel 13.45

Read article
Laravel CLI: One Binary for New PHP and Rust Laravel Apps image

Laravel CLI: One Binary for New PHP and Rust Laravel Apps

Read article
Phactorial: Render LaTeX Math to SVG and PNG in PHP image

Phactorial: Render LaTeX Math to SVG and PNG in PHP

Read article
Laravel, reimagined image

Laravel, reimagined

Read article
Laravel Rust: A New Rust Web Framework From Laravel image

Laravel Rust: A New Rust Web Framework From Laravel

Read article