0

halo everyone. now I'm trying to merge array inside array after query from SQL.. and the result like this

array(3) {
  [0]=>
  array(1) {
    ["building_id"]=>
    string(1) "1"
  }
  [1]=>
  array(1) {
    ["building_id"]=>
    string(1) "2"
  }
  [2]=>
  array(1) {
    ["building_id"]=>
    string(1) "3"
  }
}

I already tried to use this code

$result=[];
foreach($bulding_ids as $arr)
{
  $result  = array_merge($arr['building_id'],$result);
} 

but maybe that is not a answer

I want to that array become like this

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

Can I make like that?

tjandra
  • 85
  • 1
  • 2
  • 7

2 Answers2

1

You could just use array_column().

$result = array_column($building_ids, 'building_id');

array_column() returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.

This eliminates the need for a loop.

Output:

array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" }

The only downside of this, is that all of the building ID's will be stored as strings. If this is a problem for your application, you can easily use array_map() to convert them to ints.

Directly after the line above, do this:

$result = array_map('intval', $result);

array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()

Output:

array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }

You can also make this a single line solution:

$result = array_map('intval', array_column($building_ids, 'building_id'));

But in my opinion this looks a bit more messy.

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
0

You need to parse every element in your first array and return the id. Then you convert it into int type. Finally, you save the new value into a new array.

<?php
$bulding_ids[] = ["Building_id" => "1"];
$bulding_ids[] = ["Building_id" => "2"];
$bulding_ids[] = ["Building_id" => "3"];

$result = array();

foreach($bulding_ids as $val){
    $result[] = (int)$val['Building_id'];
} 

var_dump($result);
executable
  • 3,365
  • 6
  • 24
  • 52