-1

I have an API that sends me the data in the format

[{"part_no":"AAA"},{"part_no":"BBB"},{"part_no":"CCC"},......{"part_no":"ZZZ"}]

I want to create an array like ["AAA", "BBB", ...., "ZZZ"] from the above array.

I know it's possible by iterating the array item by item, and appending it to a new array, but thought that there might be a better (and hopefully faster) approach.

Like C# hasLinq that does this all in a one-liner, JS has map, it is possible to do a similar thing in PHP ?

mrid
  • 5,782
  • 5
  • 28
  • 71

1 Answers1

0
<?php

$json = '[{"part_no":"AAA"},{"part_no":"BBB"},{"part_no":"CCC"},{"part_no":"ZZZ"}]';
$data = json_decode($json, true);

$result = array_column($data, 'part_no');
var_export($result);

Output:

array (
    0 => 'AAA',
    1 => 'BBB',
    2 => 'CCC',
    3 => 'ZZZ',
  )
Progrock
  • 7,373
  • 1
  • 19
  • 25