Extract or filter specifics keys and values of a multidimensional array to another one The Next CEO of Stack OverflowHow to insert an item into an array at a specific index (JavaScript)?How do I determine whether an array contains a particular value in Java?Sort array of objects by string property valueDetermine whether an array contains a valueCheck if a value exists in an array in RubyHow to Sort Multi-dimensional Array by Value?Reference — What does this symbol mean in PHP?PHP array delete by value (not key)Copy array by valueReference - What does this error mean in PHP?

Received an invoice from my ex-employer billing me for training; how to handle?

Return the Closest Prime Number

WOW air has ceased operation, can I get my tickets refunded?

Rotate a column

Indicator light circuit

Are there any limitations on attacking while grappling?

If the heap is initialized for security, then why is the stack uninitialized?

Elegant way to replace substring in a regex with optional groups in Python?

How do I transpose the first and deepest levels of an arbitrarily nested array?

Real integral using residue theorem - why doesn't this work?

Are there any unintended negative consequences to allowing PCs to gain multiple levels at once in a short milestone-XP game?

Why do we use the plural of movies in this phrase "We went to the movies last night."?

Does it take more energy to get to Venus or to Mars?

How to start emacs in "nothing" mode (`fundamental-mode`)

Why do remote companies require working in the US?

How did people program for Consoles with multiple CPUs?

Is it possible to search for a directory/file combination?

What can we do to stop prior company from asking us questions?

Inappropriate reference requests from Journal reviewers

What is "(CFMCC)" on an ILS approach chart?

Why has the US not been more assertive in confronting Russia in recent years?

Unreliable Magic - Is it worth it?

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

What happened in Rome, when the western empire "fell"?



Extract or filter specifics keys and values of a multidimensional array to another one



The Next CEO of Stack OverflowHow to insert an item into an array at a specific index (JavaScript)?How do I determine whether an array contains a particular value in Java?Sort array of objects by string property valueDetermine whether an array contains a valueCheck if a value exists in an array in RubyHow to Sort Multi-dimensional Array by Value?Reference — What does this symbol mean in PHP?PHP array delete by value (not key)Copy array by valueReference - What does this error mean in PHP?










0















I want to filter or keep selected keys and their values in a multidimensionnal array.
I tried severals methods with array_columns, array_filter, etc ... but I'm not able to keep original structure of my array.



here is original example :



Array
(
[0] => Object
(
[not_wanted_key1] => some value
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[not_wanted_key3] => some value
[wanted_key3] => wanted value



)

[1] => Object
(
[not_wanted_key1] => some value
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[not_wanted_key3] => some value
[wanted_key3] => wanted value
)
)


expected result :



Array
(
[0] => Object
(
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[wanted_key3] => wanted value
)

[1] => Object
(
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[wanted_key3] => wanted value
)
)


Someone can guide me ?










share|improve this question






















  • In short you can't because these are objects not sub arrays.

    – ArtisticPhoenix
    Mar 7 at 15:56















0















I want to filter or keep selected keys and their values in a multidimensionnal array.
I tried severals methods with array_columns, array_filter, etc ... but I'm not able to keep original structure of my array.



here is original example :



Array
(
[0] => Object
(
[not_wanted_key1] => some value
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[not_wanted_key3] => some value
[wanted_key3] => wanted value



)

[1] => Object
(
[not_wanted_key1] => some value
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[not_wanted_key3] => some value
[wanted_key3] => wanted value
)
)


expected result :



Array
(
[0] => Object
(
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[wanted_key3] => wanted value
)

[1] => Object
(
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[wanted_key3] => wanted value
)
)


Someone can guide me ?










share|improve this question






















  • In short you can't because these are objects not sub arrays.

    – ArtisticPhoenix
    Mar 7 at 15:56













0












0








0








I want to filter or keep selected keys and their values in a multidimensionnal array.
I tried severals methods with array_columns, array_filter, etc ... but I'm not able to keep original structure of my array.



here is original example :



Array
(
[0] => Object
(
[not_wanted_key1] => some value
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[not_wanted_key3] => some value
[wanted_key3] => wanted value



)

[1] => Object
(
[not_wanted_key1] => some value
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[not_wanted_key3] => some value
[wanted_key3] => wanted value
)
)


expected result :



Array
(
[0] => Object
(
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[wanted_key3] => wanted value
)

[1] => Object
(
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[wanted_key3] => wanted value
)
)


Someone can guide me ?










share|improve this question














I want to filter or keep selected keys and their values in a multidimensionnal array.
I tried severals methods with array_columns, array_filter, etc ... but I'm not able to keep original structure of my array.



here is original example :



Array
(
[0] => Object
(
[not_wanted_key1] => some value
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[not_wanted_key3] => some value
[wanted_key3] => wanted value



)

[1] => Object
(
[not_wanted_key1] => some value
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[not_wanted_key3] => some value
[wanted_key3] => wanted value
)
)


expected result :



Array
(
[0] => Object
(
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[wanted_key3] => wanted value
)

[1] => Object
(
[wanted_key1] => wanted value
[wanted_key2] => wanted value
[wanted_key3] => wanted value
)
)


Someone can guide me ?







php arrays multidimensional-array






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 7 at 15:34









tsictsic

33




33












  • In short you can't because these are objects not sub arrays.

    – ArtisticPhoenix
    Mar 7 at 15:56

















  • In short you can't because these are objects not sub arrays.

    – ArtisticPhoenix
    Mar 7 at 15:56
















In short you can't because these are objects not sub arrays.

– ArtisticPhoenix
Mar 7 at 15:56





In short you can't because these are objects not sub arrays.

– ArtisticPhoenix
Mar 7 at 15:56












3 Answers
3






active

oldest

votes


















0














You can do it like this:



//test data
$array[] = new stdClass;
$array[0]->not_wanted_key1 = '1';
$array[0]->not_wanted_key2 = '3';
$array[0]->wanted_key1 = '4';
$array[0]->wanted_key2 = '5';
$array[0]->wanted_key3 = '6';

print_r($array);


$map = array_flip(['wanted_key1', 'wanted_key2', 'wanted_key3']);

$res = array_map(function($item) use ($map)
return array_intersect_key((array) $item, $map);
, $array);


print_r($res);


Output



//input array
Array
(
[0] => stdClass Object
(
[not_wanted_key1] => 1
[not_wanted_key2] => 3
[wanted_key1] => 4
[wanted_key2] => 5
[wanted_key3] => 6
)

)
//output array
Array
(
[0] => Array
(
[wanted_key1] => 4
[wanted_key2] => 5
[wanted_key3] => 6
)

)


Sandbox



Pretty simple, the trick is (array) casting the object to an array, and then I like to use array_intersect_key but I am to lazy to manually do $map so I just flip the values around to be the keys.



This way you can easily add/remove keys you want to keep, just by adding/removing them from $map.



If you want to keep the inner array as an object you can cast it back too! so change this:



 return array_intersect_key((array) $item, $map);


To



 return (object)array_intersect_key((array) $item, $map);


Output



Array
(
[0] => stdClass Object
(
[wanted_key1] => 4
[wanted_key2] => 5
[wanted_key3] => 6
)
)


Sandbox



To be clear all you need is this, the rest is for testing:



$map = array_flip(['wanted_key1', 'wanted_key2', 'wanted_key3']);
$res = array_map(function($item)use($map)return array_intersect_key((array)$item,$map);,$array);





share|improve this answer

























  • sorry for late answer but thanks ! This is exactly what I wanted :)

    – tsic
    Mar 15 at 8:48



















0














array_filter() should do the work.



Simple example:



$original = ['a' => 2, 'b' => 5, 'c' => 6];

$filtered = array_filter($original, function($item)
// This anonymous function must return true for keeping your item, or false for not keeping it

// There I want to keep items with a value more than 4.
return ($item > 4);
);

// Output of $filtered: ['b' => 5, 'c' => 6]


Same example with an array of objects, supposing these have a value property:



$filtered = array_filter($original, function($item) 
// There I want to keep items with a value more than 4.
return ($item->value > 4);
);

// Output of $filtered: ['b' => 5, 'c' => 6]


If your logic is about filtering from keys, the third parameter flag must be set to ARRAY_FILTER_USE_KEY. Then $item will be your keys, not values.






share|improve this answer

























  • keys I want to keep are same in all objects but "values" are differents for all those and not necessary numeric. I want to keep wanted_key1, 2 and 3 and their associated different "value"

    – tsic
    Mar 7 at 16:10



















0














Similar to ArtisticPheonix's answer, loop through and keep the keys we want by using an intersection:



<?php

$data =
[
['fruit'=>'apple', 'veg'=>'carrot'],
['fruit'=>'banana', 'veg'=>'marrow']
];

$flipped_wanted_keys = array_flip(['fruit']);
foreach($data as &$item)
$item = array_intersect_key($item, $flipped_wanted_keys);

unset($item);
print_r($data);


Output:



Array
(
[0] => Array
(
[fruit] => apple
)

[1] => Array
(
[fruit] => banana
)

)


As you have objects in your array, removing properties requires a different approach, but if you are happy to have a multidimensional array as above as the output, then you just need to cast your object to an array before the key intersection (assuming these are accessible properties).



$item = array_intersect_key((array) $item, $flipped_wanted_keys);





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55047519%2fextract-or-filter-specifics-keys-and-values-of-a-multidimensional-array-to-anoth%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    You can do it like this:



    //test data
    $array[] = new stdClass;
    $array[0]->not_wanted_key1 = '1';
    $array[0]->not_wanted_key2 = '3';
    $array[0]->wanted_key1 = '4';
    $array[0]->wanted_key2 = '5';
    $array[0]->wanted_key3 = '6';

    print_r($array);


    $map = array_flip(['wanted_key1', 'wanted_key2', 'wanted_key3']);

    $res = array_map(function($item) use ($map)
    return array_intersect_key((array) $item, $map);
    , $array);


    print_r($res);


    Output



    //input array
    Array
    (
    [0] => stdClass Object
    (
    [not_wanted_key1] => 1
    [not_wanted_key2] => 3
    [wanted_key1] => 4
    [wanted_key2] => 5
    [wanted_key3] => 6
    )

    )
    //output array
    Array
    (
    [0] => Array
    (
    [wanted_key1] => 4
    [wanted_key2] => 5
    [wanted_key3] => 6
    )

    )


    Sandbox



    Pretty simple, the trick is (array) casting the object to an array, and then I like to use array_intersect_key but I am to lazy to manually do $map so I just flip the values around to be the keys.



    This way you can easily add/remove keys you want to keep, just by adding/removing them from $map.



    If you want to keep the inner array as an object you can cast it back too! so change this:



     return array_intersect_key((array) $item, $map);


    To



     return (object)array_intersect_key((array) $item, $map);


    Output



    Array
    (
    [0] => stdClass Object
    (
    [wanted_key1] => 4
    [wanted_key2] => 5
    [wanted_key3] => 6
    )
    )


    Sandbox



    To be clear all you need is this, the rest is for testing:



    $map = array_flip(['wanted_key1', 'wanted_key2', 'wanted_key3']);
    $res = array_map(function($item)use($map)return array_intersect_key((array)$item,$map);,$array);





    share|improve this answer

























    • sorry for late answer but thanks ! This is exactly what I wanted :)

      – tsic
      Mar 15 at 8:48
















    0














    You can do it like this:



    //test data
    $array[] = new stdClass;
    $array[0]->not_wanted_key1 = '1';
    $array[0]->not_wanted_key2 = '3';
    $array[0]->wanted_key1 = '4';
    $array[0]->wanted_key2 = '5';
    $array[0]->wanted_key3 = '6';

    print_r($array);


    $map = array_flip(['wanted_key1', 'wanted_key2', 'wanted_key3']);

    $res = array_map(function($item) use ($map)
    return array_intersect_key((array) $item, $map);
    , $array);


    print_r($res);


    Output



    //input array
    Array
    (
    [0] => stdClass Object
    (
    [not_wanted_key1] => 1
    [not_wanted_key2] => 3
    [wanted_key1] => 4
    [wanted_key2] => 5
    [wanted_key3] => 6
    )

    )
    //output array
    Array
    (
    [0] => Array
    (
    [wanted_key1] => 4
    [wanted_key2] => 5
    [wanted_key3] => 6
    )

    )


    Sandbox



    Pretty simple, the trick is (array) casting the object to an array, and then I like to use array_intersect_key but I am to lazy to manually do $map so I just flip the values around to be the keys.



    This way you can easily add/remove keys you want to keep, just by adding/removing them from $map.



    If you want to keep the inner array as an object you can cast it back too! so change this:



     return array_intersect_key((array) $item, $map);


    To



     return (object)array_intersect_key((array) $item, $map);


    Output



    Array
    (
    [0] => stdClass Object
    (
    [wanted_key1] => 4
    [wanted_key2] => 5
    [wanted_key3] => 6
    )
    )


    Sandbox



    To be clear all you need is this, the rest is for testing:



    $map = array_flip(['wanted_key1', 'wanted_key2', 'wanted_key3']);
    $res = array_map(function($item)use($map)return array_intersect_key((array)$item,$map);,$array);





    share|improve this answer

























    • sorry for late answer but thanks ! This is exactly what I wanted :)

      – tsic
      Mar 15 at 8:48














    0












    0








    0







    You can do it like this:



    //test data
    $array[] = new stdClass;
    $array[0]->not_wanted_key1 = '1';
    $array[0]->not_wanted_key2 = '3';
    $array[0]->wanted_key1 = '4';
    $array[0]->wanted_key2 = '5';
    $array[0]->wanted_key3 = '6';

    print_r($array);


    $map = array_flip(['wanted_key1', 'wanted_key2', 'wanted_key3']);

    $res = array_map(function($item) use ($map)
    return array_intersect_key((array) $item, $map);
    , $array);


    print_r($res);


    Output



    //input array
    Array
    (
    [0] => stdClass Object
    (
    [not_wanted_key1] => 1
    [not_wanted_key2] => 3
    [wanted_key1] => 4
    [wanted_key2] => 5
    [wanted_key3] => 6
    )

    )
    //output array
    Array
    (
    [0] => Array
    (
    [wanted_key1] => 4
    [wanted_key2] => 5
    [wanted_key3] => 6
    )

    )


    Sandbox



    Pretty simple, the trick is (array) casting the object to an array, and then I like to use array_intersect_key but I am to lazy to manually do $map so I just flip the values around to be the keys.



    This way you can easily add/remove keys you want to keep, just by adding/removing them from $map.



    If you want to keep the inner array as an object you can cast it back too! so change this:



     return array_intersect_key((array) $item, $map);


    To



     return (object)array_intersect_key((array) $item, $map);


    Output



    Array
    (
    [0] => stdClass Object
    (
    [wanted_key1] => 4
    [wanted_key2] => 5
    [wanted_key3] => 6
    )
    )


    Sandbox



    To be clear all you need is this, the rest is for testing:



    $map = array_flip(['wanted_key1', 'wanted_key2', 'wanted_key3']);
    $res = array_map(function($item)use($map)return array_intersect_key((array)$item,$map);,$array);





    share|improve this answer















    You can do it like this:



    //test data
    $array[] = new stdClass;
    $array[0]->not_wanted_key1 = '1';
    $array[0]->not_wanted_key2 = '3';
    $array[0]->wanted_key1 = '4';
    $array[0]->wanted_key2 = '5';
    $array[0]->wanted_key3 = '6';

    print_r($array);


    $map = array_flip(['wanted_key1', 'wanted_key2', 'wanted_key3']);

    $res = array_map(function($item) use ($map)
    return array_intersect_key((array) $item, $map);
    , $array);


    print_r($res);


    Output



    //input array
    Array
    (
    [0] => stdClass Object
    (
    [not_wanted_key1] => 1
    [not_wanted_key2] => 3
    [wanted_key1] => 4
    [wanted_key2] => 5
    [wanted_key3] => 6
    )

    )
    //output array
    Array
    (
    [0] => Array
    (
    [wanted_key1] => 4
    [wanted_key2] => 5
    [wanted_key3] => 6
    )

    )


    Sandbox



    Pretty simple, the trick is (array) casting the object to an array, and then I like to use array_intersect_key but I am to lazy to manually do $map so I just flip the values around to be the keys.



    This way you can easily add/remove keys you want to keep, just by adding/removing them from $map.



    If you want to keep the inner array as an object you can cast it back too! so change this:



     return array_intersect_key((array) $item, $map);


    To



     return (object)array_intersect_key((array) $item, $map);


    Output



    Array
    (
    [0] => stdClass Object
    (
    [wanted_key1] => 4
    [wanted_key2] => 5
    [wanted_key3] => 6
    )
    )


    Sandbox



    To be clear all you need is this, the rest is for testing:



    $map = array_flip(['wanted_key1', 'wanted_key2', 'wanted_key3']);
    $res = array_map(function($item)use($map)return array_intersect_key((array)$item,$map);,$array);






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 7 at 16:12

























    answered Mar 7 at 16:01









    ArtisticPhoenixArtisticPhoenix

    18.1k11226




    18.1k11226












    • sorry for late answer but thanks ! This is exactly what I wanted :)

      – tsic
      Mar 15 at 8:48


















    • sorry for late answer but thanks ! This is exactly what I wanted :)

      – tsic
      Mar 15 at 8:48

















    sorry for late answer but thanks ! This is exactly what I wanted :)

    – tsic
    Mar 15 at 8:48






    sorry for late answer but thanks ! This is exactly what I wanted :)

    – tsic
    Mar 15 at 8:48














    0














    array_filter() should do the work.



    Simple example:



    $original = ['a' => 2, 'b' => 5, 'c' => 6];

    $filtered = array_filter($original, function($item)
    // This anonymous function must return true for keeping your item, or false for not keeping it

    // There I want to keep items with a value more than 4.
    return ($item > 4);
    );

    // Output of $filtered: ['b' => 5, 'c' => 6]


    Same example with an array of objects, supposing these have a value property:



    $filtered = array_filter($original, function($item) 
    // There I want to keep items with a value more than 4.
    return ($item->value > 4);
    );

    // Output of $filtered: ['b' => 5, 'c' => 6]


    If your logic is about filtering from keys, the third parameter flag must be set to ARRAY_FILTER_USE_KEY. Then $item will be your keys, not values.






    share|improve this answer

























    • keys I want to keep are same in all objects but "values" are differents for all those and not necessary numeric. I want to keep wanted_key1, 2 and 3 and their associated different "value"

      – tsic
      Mar 7 at 16:10
















    0














    array_filter() should do the work.



    Simple example:



    $original = ['a' => 2, 'b' => 5, 'c' => 6];

    $filtered = array_filter($original, function($item)
    // This anonymous function must return true for keeping your item, or false for not keeping it

    // There I want to keep items with a value more than 4.
    return ($item > 4);
    );

    // Output of $filtered: ['b' => 5, 'c' => 6]


    Same example with an array of objects, supposing these have a value property:



    $filtered = array_filter($original, function($item) 
    // There I want to keep items with a value more than 4.
    return ($item->value > 4);
    );

    // Output of $filtered: ['b' => 5, 'c' => 6]


    If your logic is about filtering from keys, the third parameter flag must be set to ARRAY_FILTER_USE_KEY. Then $item will be your keys, not values.






    share|improve this answer

























    • keys I want to keep are same in all objects but "values" are differents for all those and not necessary numeric. I want to keep wanted_key1, 2 and 3 and their associated different "value"

      – tsic
      Mar 7 at 16:10














    0












    0








    0







    array_filter() should do the work.



    Simple example:



    $original = ['a' => 2, 'b' => 5, 'c' => 6];

    $filtered = array_filter($original, function($item)
    // This anonymous function must return true for keeping your item, or false for not keeping it

    // There I want to keep items with a value more than 4.
    return ($item > 4);
    );

    // Output of $filtered: ['b' => 5, 'c' => 6]


    Same example with an array of objects, supposing these have a value property:



    $filtered = array_filter($original, function($item) 
    // There I want to keep items with a value more than 4.
    return ($item->value > 4);
    );

    // Output of $filtered: ['b' => 5, 'c' => 6]


    If your logic is about filtering from keys, the third parameter flag must be set to ARRAY_FILTER_USE_KEY. Then $item will be your keys, not values.






    share|improve this answer















    array_filter() should do the work.



    Simple example:



    $original = ['a' => 2, 'b' => 5, 'c' => 6];

    $filtered = array_filter($original, function($item)
    // This anonymous function must return true for keeping your item, or false for not keeping it

    // There I want to keep items with a value more than 4.
    return ($item > 4);
    );

    // Output of $filtered: ['b' => 5, 'c' => 6]


    Same example with an array of objects, supposing these have a value property:



    $filtered = array_filter($original, function($item) 
    // There I want to keep items with a value more than 4.
    return ($item->value > 4);
    );

    // Output of $filtered: ['b' => 5, 'c' => 6]


    If your logic is about filtering from keys, the third parameter flag must be set to ARRAY_FILTER_USE_KEY. Then $item will be your keys, not values.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 7 at 16:05

























    answered Mar 7 at 15:42









    iArcadiaiArcadia

    1,152619




    1,152619












    • keys I want to keep are same in all objects but "values" are differents for all those and not necessary numeric. I want to keep wanted_key1, 2 and 3 and their associated different "value"

      – tsic
      Mar 7 at 16:10


















    • keys I want to keep are same in all objects but "values" are differents for all those and not necessary numeric. I want to keep wanted_key1, 2 and 3 and their associated different "value"

      – tsic
      Mar 7 at 16:10

















    keys I want to keep are same in all objects but "values" are differents for all those and not necessary numeric. I want to keep wanted_key1, 2 and 3 and their associated different "value"

    – tsic
    Mar 7 at 16:10






    keys I want to keep are same in all objects but "values" are differents for all those and not necessary numeric. I want to keep wanted_key1, 2 and 3 and their associated different "value"

    – tsic
    Mar 7 at 16:10












    0














    Similar to ArtisticPheonix's answer, loop through and keep the keys we want by using an intersection:



    <?php

    $data =
    [
    ['fruit'=>'apple', 'veg'=>'carrot'],
    ['fruit'=>'banana', 'veg'=>'marrow']
    ];

    $flipped_wanted_keys = array_flip(['fruit']);
    foreach($data as &$item)
    $item = array_intersect_key($item, $flipped_wanted_keys);

    unset($item);
    print_r($data);


    Output:



    Array
    (
    [0] => Array
    (
    [fruit] => apple
    )

    [1] => Array
    (
    [fruit] => banana
    )

    )


    As you have objects in your array, removing properties requires a different approach, but if you are happy to have a multidimensional array as above as the output, then you just need to cast your object to an array before the key intersection (assuming these are accessible properties).



    $item = array_intersect_key((array) $item, $flipped_wanted_keys);





    share|improve this answer





























      0














      Similar to ArtisticPheonix's answer, loop through and keep the keys we want by using an intersection:



      <?php

      $data =
      [
      ['fruit'=>'apple', 'veg'=>'carrot'],
      ['fruit'=>'banana', 'veg'=>'marrow']
      ];

      $flipped_wanted_keys = array_flip(['fruit']);
      foreach($data as &$item)
      $item = array_intersect_key($item, $flipped_wanted_keys);

      unset($item);
      print_r($data);


      Output:



      Array
      (
      [0] => Array
      (
      [fruit] => apple
      )

      [1] => Array
      (
      [fruit] => banana
      )

      )


      As you have objects in your array, removing properties requires a different approach, but if you are happy to have a multidimensional array as above as the output, then you just need to cast your object to an array before the key intersection (assuming these are accessible properties).



      $item = array_intersect_key((array) $item, $flipped_wanted_keys);





      share|improve this answer



























        0












        0








        0







        Similar to ArtisticPheonix's answer, loop through and keep the keys we want by using an intersection:



        <?php

        $data =
        [
        ['fruit'=>'apple', 'veg'=>'carrot'],
        ['fruit'=>'banana', 'veg'=>'marrow']
        ];

        $flipped_wanted_keys = array_flip(['fruit']);
        foreach($data as &$item)
        $item = array_intersect_key($item, $flipped_wanted_keys);

        unset($item);
        print_r($data);


        Output:



        Array
        (
        [0] => Array
        (
        [fruit] => apple
        )

        [1] => Array
        (
        [fruit] => banana
        )

        )


        As you have objects in your array, removing properties requires a different approach, but if you are happy to have a multidimensional array as above as the output, then you just need to cast your object to an array before the key intersection (assuming these are accessible properties).



        $item = array_intersect_key((array) $item, $flipped_wanted_keys);





        share|improve this answer















        Similar to ArtisticPheonix's answer, loop through and keep the keys we want by using an intersection:



        <?php

        $data =
        [
        ['fruit'=>'apple', 'veg'=>'carrot'],
        ['fruit'=>'banana', 'veg'=>'marrow']
        ];

        $flipped_wanted_keys = array_flip(['fruit']);
        foreach($data as &$item)
        $item = array_intersect_key($item, $flipped_wanted_keys);

        unset($item);
        print_r($data);


        Output:



        Array
        (
        [0] => Array
        (
        [fruit] => apple
        )

        [1] => Array
        (
        [fruit] => banana
        )

        )


        As you have objects in your array, removing properties requires a different approach, but if you are happy to have a multidimensional array as above as the output, then you just need to cast your object to an array before the key intersection (assuming these are accessible properties).



        $item = array_intersect_key((array) $item, $flipped_wanted_keys);






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 7 at 18:25

























        answered Mar 7 at 16:23









        ProgrockProgrock

        4,48011022




        4,48011022



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55047519%2fextract-or-filter-specifics-keys-and-values-of-a-multidimensional-array-to-anoth%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

            Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

            Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved