PHP code example of softboxlab / php-array-utils

1. Go to this page and download the library: Download softboxlab/php-array-utils library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

softboxlab / php-array-utils example snippets


class Example {
    public function test() {
        $value = [
            "a" => [
                "b" => [
                    "c1" => "a",
                    "c2" => "2",
                    "c3" => "3",
                    "c4" => ["1", "2", "3"],
                    "c5" => [
                        ["d1" => "9"],
                        ["d1" => "8"],
                        ["d1" => "7"],
                    ]
                ]
            ]
        ];
    
        // 1. Create a instance of CastHelper
        // 2. Configure the rules to cast values
        // 3. Execute method 'cast' to cast array values
        
        $ret = (new CastHelper())
            ->addRule("a.b.c1", "string")
            ->addRule("a.b.c2", "int")
            ->addRule("a.b.c3", "float")
            ->addRule("a.b.c4.*", "int")
            ->addRule("a.b.c5.*.d1", "string|lpad:2,0")
            ->cast($value);

        echo "\n\n" . json_encode($ret, JSON_PRETTY_PRINT);
    }
}


    [ 
        "a" => [
            "b" => "value"
        ]
    ]; 

    [ 
        "a" => [
            [ "b" => "zero" ],
            [ "b" => "one" ],
            [ "b" => "two" ],
            [ "b" => "three" ]
        ]
    ]; 

    [ 
        "a" => [
            [ "b" => "zero" ],
            [ "b" => "one" ],
            [ "b" => "two" ],
            [ "b" => "three" ]
        ]
    ]; 
\Cast\CastRule\CastRuleFactory::registerCastRule
\Cast\CastRule\CastRuleBase

class BooleanCastRule extends PHP\Cast\CastRule\CastRuleBase {
    public function getIdentifier() {
        return "bool";
    }

    public function cast($value) {
        return (boolean) $value;
    }
} 

...

PHP\Cast\CastRule\CastRuleFactory::registerCastRule(new BooleanCastRule());

...

composer