1

I am new to postgresql with php. I get below array using pg_fetch_array() function.

Array
(
    [0] => 
    [name] => 
    [1] => 1
    [status] => 1
    [2] => C2005
    [code] => C2005
)

after removing index 1 and value of key status, i have to reindex this array so that expected output should become like:

Array
(
    [0] => 
    [name] => 
    [1] => C2005
    [code] => C2005
)

I tried

unset($row[1]);
unset($row['status'];
$foo = array_values($row);
echo "<pre>";
print_r($foo)
echo "</pre>";

and got output

Array
(
    [0] => 
    [name] => 
    [2] => C2005
    [code] => C2005
)

How the numeric index can be re-indexed after removing particular keys from the array?

LF00
  • 27,015
  • 29
  • 156
  • 295
deltaforce
  • 85
  • 1
  • 1
  • 11
  • Use `pg_fetch_assoc()` instead of `pg_fetch_array()` then you wont get the numerically indexed columns, it will return only the named columns – RiggsFolly Apr 18 '17 at 09:38
  • Alternatively use `pg_fetch_array($result, NULL, PGSQL_ASSOC);` to just get the associative array – RiggsFolly Apr 18 '17 at 09:40
  • 1
    why you don't only select the `name, code` in your select statement ? – hassan Apr 18 '17 at 09:40
  • and how could `array_values` returns with associated array ? it **must** returns with numeric array – hassan Apr 18 '17 at 09:43
  • As this is an existing code of live application, so i can not make any further changes. the field status is injected in the main query for some reason but later on it needs to be removed from the result. Is there any way we can re-index the array after removing particular key values? – deltaforce Apr 18 '17 at 09:53

1 Answers1

0

You can filter the array by their key. Live demo.

unset($array['status']);
$number_keys = array_values(array_filter($array, function($k){return is_int($k) && $k != 1;}, ARRAY_FILTER_USE_KEY));
$nonnumber_keys = array_filter($array, function($k){return is_string($k);}, ARRAY_FILTER_USE_KEY);
$result = array_merge($number_keys, $nonnumber_keys);
LF00
  • 27,015
  • 29
  • 156
  • 295
  • it did not work. i printed $result after replacing $array in your example with my array variable – deltaforce Apr 18 '17 at 10:06
  • It worked !! Thanks for providing live demo. I observed that i was missing something. But now your solution is working for me. – deltaforce Apr 19 '17 at 11:41