PHP code example of alleyinteractive / traverse-reshape

1. Go to this page and download the library: Download alleyinteractive/traverse-reshape 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/ */

    

alleyinteractive / traverse-reshape example snippets




$arr = [
    'apples' => [
        'red' => [
            'gala',
            'mcintosh',
        ],
        'green' => [
            'granny_smith',
        ],
    ],
];

$obj = (object) [
    'apples' => (object) [
        'red' => [
            'gala',
            'mcintosh',
        ],
        'green' => [
            'granny_smith',
        ],
    ],
];


$green = \Alley\traverse($arr, 'apples.green');
// ['granny_smith']

$red = \Alley\traverse($obj, 'apples.red');
// ['gala', 'mcintosh']

[$red, $green] = \Alley\traverse($obj, ['apples.red', 'apples.green']);
// ['gala', 'mcintosh'], ['granny_smith']

[[$red, $green]] = \Alley\traverse(
    $obj,
    [
        'apples' => [
            'red',
            'green',
       ],
   ],
);
// ['gala', 'mcintosh'], ['granny_smith']
// note the extra depth of the return value -- values are nested according to the nesting of the given paths

[$red] = \Alley\traverse($obj, ['apples' => 'red']);
// ['gala', 'mcintosh']

$sweet = \Alley\traverse($arr, 'apples.green.sweet');
// NULL

$pears = \Alley\traverse($arr, 'pears');
// NULL

$req = getRemoteData();
[$title, $date] = \Alley\traverse($req, ['title', 'date']);
// $title and $date variables are guaranteed defined regardless of $req

[[$red, $green], $title] = \Alley\traverse(
    [$arr, $req],
    [
        '0.apples' => ['red', 'green'],
        '1.title',
   ]
);



$original = [
    'id' => 1,
    'title' => [
        'rendered' => 'Hello world!',
    ],
    'content' => [
        'rendered' => '<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>',
    ],
    'categories' => [1],
    'tags' => [],
    '_links' => [
        'self' => [
            [
                'href' => 'https://www.example.com/wp-json/wp/v2/posts/1',
            ],
        ],
    ],
];

\Alley\reshape(
    $original,
    [
        'title' => 'title.rendered',
        'dek' => 'meta.dek',
        'content.rendered',
        'term_ids' => (object) [
            'category' => 'categories',
            'post_tag' => 'tags',
        ],
        'json' => '_links.self.0.href',
    ]
);

/*
    [
        'title' => 'Hello world!',
        'dek' => NULL,
        'rendered' => '<p>Welcome to WordPress...',
        'term_ids' => (object) [
            'category' => [1],
            'post_tag' => [],
        ],
        'json' => 'https://www.example.com/...',
    ]
*/