Brett Williams
Brett Williams

Reputation: 173

Convert associative array of strings to flat array of integer (values only)

I cant figure out how to get Array 1 and make it look like Array 2 so that I can send it as parameters for my prepared statements method.

ARRAY 1: (what I currently have)

array(5) { [0]=> array(2) { ["id"]=> string(1) "1" [0]=> string(1) "1" } [1]=> array(2) { ["id"]=> string(3) "314" [0]=> string(3) "314" } [2]=> array(2) { ["id"]=> string(3) "315" [0]=> string(3) "315" } [3]=> array(2) { ["id"]=> string(3) "316" [0]=> string(3) "316" } [4]=> array(2) { ["id"]=> string(3) "317" [0]=> string(3) "317" } } 

ARRAY 2: What I'm trying to get it to be. (please ignore that 1 item is missing)

array(4) { [0]=> int(314) [1]=> int(315) [2]=> int(316) [3]=> int(317) }

I'm trying to accomplish this in PHP php7.1 if that matters.

I THINK this is enough information but if its not please let me know. I just didnt want to bog you down with all sorts of code and explanation that I'm not sure you need.

What I've tried so far (although possibly not properly):

$category_ids2 = array_values($category_ids);

Upvotes: 5

Views: 2661

Answers (3)

jh1711
jh1711

Reputation: 2328

First use array_column to flatten the array. Then combine array_map with intval to cast the strings to integers. All together:

$category_ids2 = array_map('intval', array_column($category_ids, 'id'));

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

There's a function for extracting one column and another for converting to integer:

$category_ids = array_map('intval', array_column($category_ids, 'id'));

Without array_column:

$category_ids = array_map(function($v) { return (int)$v['id']; }, $category_ids);

However, this looks suspiciously like database results. If so, then just build the array the way you want when fetching the results. Also, using the fetch assoc of your database library would eliminate the 0 index in each array.

Upvotes: 5

Krish
Krish

Reputation: 387

$array = [['id' => '1', '0' => '1'], 
      ['id' => '314', '0' => '314'],
      ['id' => '315', '0' => '315'],
      ['id' => '316', '0' => '316'],
      ['id' => '317', '0' => '317']];

echo "<pre>";

$ids = array_column($array, 'id');


unset($ids['0']); 
var_dump($ids);

$integerIDs = array_map('intval', $ids);

var_dump($integerIDs);

Explanation:

  1. you should use array_column to get ids http://php.net/manual/en/function.array-column.php
  2. then unset if position zero is not required
  3. array_map('intval', $ids); each and every values will be converted into int

Upvotes: 1

Related Questions