Skip to content
Advertisement

json encode specific object’s property

I have an array:

[
    (int) 0 => object(stdClass) {
        key1 => 'aaa'
        key2 => 'bbb'
        key3 => 'ccc'
    },
    (int) 1 => object(stdClass) {
        key1 => 'ddd'
        key2 => 'eee'
        key3 => 'fff'
    },
    (int) 2 => object(stdClass) {
        key1 => 'ggg'
        key2 => 'hhh'
        key3 => 'iii'
    }
]

I want to return a json_encode for this array, but only for “key2” and “key3” attributes.

For the moment that:

foreach($myArray as $key){
    unset($key->key1);
}

But this is not okay as the array may also contain other properties. If it is possible, I prefer not to use loops…

(sorry for my english)

Advertisement

Answer

This solution uses array_map() and array_intersect_key():

<?php

$data = [
  ['key1' => 'aaa', 'key2' => 'bbb', 'key3' => 'ccc'],
  ['key1' => 'ddd', 'key2' => 'eee', 'key3' => 'fff'],
  ['key1' => 'ggg', 'key2' => 'hhh', 'key3' => 'iii']
];

/**
 * define allowed keys
 *
 * array_flip() exchanges the keys with their values
 * so it becomes ['key2' => 0, 'key3' => 1]
 * useful for array_intersect_key() later on
 *
 */
$allowed = array_flip(['key2', 'key3']);

$newData = array_map(
  function($item) use ($allowed) {
    return array_intersect_key($item, $allowed); 
  }, 
  $data
);

echo json_encode($newData);

…which prints:

[{"key2":"bbb","key3":"ccc"},{"key2":"eee","key3":"fff"},{"key2":"hhh","key3":"iii"}]
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement