-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 ?

8
  • 1
    $out = array_map(fn($item) => $item['part_no'], $in); or, if it's a simple associative array: $out = array_column($in, 'part_no'); Commented Sep 30, 2020 at 8:44
  • Prior to PHP7.4: $out = array_map(function ($part) { return $part['part_no']; }, json_decode($data, true)); Commented Sep 30, 2020 at 8:47
  • and hopefully faster Of course there are one liners in PHP, but it is not faster than looping. Commented Sep 30, 2020 at 8:52
  • @Nick I'm using 7.2, and your code returns null Commented Sep 30, 2020 at 9:22
  • Is your JSON variable called $data? Commented Sep 30, 2020 at 9:27

1 Answer 1

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',
  )
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.