Finding array keys from a vector

3

I have an array where the indexes "parents" are not indexed with underlines and the children are. Every time a parent receives a child, all other parents also receive a child.

Example we have 2 children:

array(
  x = array()
  x_1 = array()
  x_2 = array()
  y = array()
  y_1 = array()
  y_2 = array()
);

I need to get all indexes that are parents, in this case x and y. The solution I found would be to traverse the vector looking for indexes that have no underline, but I did not find a pretty solution, as I would have to go through the vector again to add new children.

Would anyone have a simpler and / or more beautiful solution?

    
asked by anonymous 31.03.2016 / 03:57

1 answer

1

You can use preg_filter for this, so filter only where there is "no" underline, or any other character.

By default the regex returns only data that exists, but there is a way to reverse this.

Well, overall this is it:

<?php

// Sua array!
$array = array(
  'x' => array(),
  'x_1' => array(),
  'x_2' => array(),
  'y' => array(),
  'y_1' => array(),
  'y_2' => array(),
);

// Filtro para apenas sem _
$filtro = preg_filter('/^((?!_).)*$/', '$1', array_keys( $array ));

// Exibe o $filtro
print_r($filtro);

The return will be:

Array ( [0] => x [3] => y ) 

You can test this by clicking here!

    
31.03.2016 / 21:31