Remove all array elements except what I want?

Solution 1:

By whitelisting the entries you do expect.

<?php
$post = array( 
    'parent_id' => 1,
    'type' => 'foo', 
    'title' => 'bar', 
    'body' => 'foo bar', 
    'tags' => 'foo, bar', 
    'one' => 'foo',
    'two' => 'bar',
    'three' => 'qux'
);

$whitelist = array(
    'parent_id',
    'type',
    'title',
    'body',
    'tags'
);

$filtered = array_intersect_key( $post, array_flip( $whitelist ) );

var_dump( $filtered );

Anyway, using Cassandra as a data-store is of course not a reason not to do validation on the data you're receiving.

Solution 2:

You are looking for array_intersect:

$good = ['parent_id', 'type', 'title', 'body', 'tags'];
$post = ['parent_id', 'type', 'title', 'body', 'tags', 'one', 'two', 'three'];

print_r(array_intersect($good, $post));

See it in action.

Of course this specific example does not make much sense because it works on array values, but there is also array_intersect_key that does the same based on keys.

Solution 3:

What about multidimensional array? I was researched for a couple of hours for this solution, nowhere found an optimal solution. so, i wrote it by myself

function allow_keys($arr, $keys)
    {
        $saved = [];

        foreach ($keys as $key => $value) {
            if (is_int($key) || is_int($value)) {
                $keysKey = $value;
            } else {
                $keysKey = $key;
            }
            if (isset($arr[$keysKey])) {

                $saved[$keysKey] = $arr[$keysKey];
                if (is_array($value)) {

                    $saved[$keysKey] = allow_keys($saved[$keysKey], $keys[$keysKey]);
                }
            }
        }
        return $saved;
    }

use: example

$array = [
        'key1' => 'kw',
        'loaa'=> ['looo'],
        'k'    => [
            'prope' => [
                'prop'  => ['proo', 'prot', 'loolooo', 'de'],
                'prop2' => ['hun' => 'lu'],
            ],
            'prop1' => [

            ],
        ],
    ];

call: example

allow_keys($array, ['key1', 'k' => ['prope' => ['prop' => [0, 1], 'prop2']]])

output:

Array ( [key1] => kw [k] => Array ( [prope] => Array ( [prop] => Array ( [0] => proo [1] => prot ) [prop2] => Array ( [hun] => lu ) ) ) ) 

so you get only needed keys from the multidimensional array. it is not limited only for "multidimensional", you can use it by passing an array like

['key1', 'loaa']

output you get:

Array ( [key1] => kw [loaa] => Array ( [0] => looo ) )

cheers!