How can I simplify this array?

I have this array:

Array
(
    [0] => Array
        (
            [tag_id] => 1
        )

    [2] => Array
        (
            [tag_id] => 3
        )

    [22] => Array
        (
            [tag_id] => 44
        )

    [23] => Array
        (
            [tag_id] => 45
        )

    [25] => Array
        (
            [tag_id] => 47
        )

    [26] => Array
        (
            [tag_id] => 48
        )

)

I would like it to look something like this, so it was easier for me to scroll and paste each value into the database:

Array
(
    [0] => 1
    [1] => 3
    [2] => 44
    [3] => 45
    [4] => 47
    [5] => 48
)
+3
source share
3 answers

You can use array_map .

PHP 5.3 or later:

$callback = function($value) {
   return $value['tag_id'];
};
$result = array_map($callback, $array);

Below 5.3:

function collapseTagIds($value) {
  return $value['tag_id'];
}
$result = array_map('collapseTagIds', $array);
+8
source

Ok, you could do this:

$new_array = array();
foreach($array as $key => $value)
{
    $new_array[$key] = $value['tag_id'];
}
print_r($new_array);
+3
source

In your case, you only have one index per $value. If you do not want to specify an index name, just do it:

$new_array = array();
foreach($array as $key => $value) {
  $new_array[$key] = reset($value);
}
print_r($new_array);
+1
source

Source: https://habr.com/ru/post/1758808/


All Articles