Home > Software engineering >  json encode specific object's property
json encode specific object's property

Time:10-24

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)

CodePudding user response:

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"}]

CodePudding user response:

This can be accomplished using array_map over the array and creating a new array of objects with only the attributes you want.

<?php

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

$obj = json_decode(json_encode($arr)); // to turn sample data into objects

$output = array_map(function ($e) {
    $new_obj = new stdClass;
    $new_obj->key2 = $e->key2;
    $new_obj->key3 = $e->key3;
    return $new_obj;
}, $obj);

var_dump($output);

Results in

array(3) {
  [0]=>
  object(stdClass)#5 (2) {
    ["key2"]=>
    string(3) "bbb"
    ["key3"]=>
    string(3) "ccc"
  }
  [1]=>
  object(stdClass)#6 (2) {
    ["key2"]=>
    string(3) "eee"
    ["key3"]=>
    string(3) "fff"
  }
  [2]=>
  object(stdClass)#7 (2) {
    ["key2"]=>
    string(3) "hhh"
    ["key3"]=>
    string(3) "iii"
  }
}
  • Related