简体   繁体   中英

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'd like it to look something like this so its simpler for me to loop through and insert each value into a database:

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

You can use array_map .

PHP 5.3 or higher:

$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);

Well, you could do this:

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

In your case, you have just one index on $value . If you don't want to specify the index name just do it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM