Discover Keys array of a vector

Asked

Viewed 47 times

3

I have an array where the "parents" indexes are not indexed with underlines and the children are. Every time a parent receives a child, every other parent also receives 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 the indices that are parents, in this case x and y. The solution I found would be to go through the vector searching for indexes that have no underline, but I did not find a beautiful solution, because I would have to go through the vector once again to add new children.

Someone would have a simpler and/or more beautiful solution?

  • You have already analyzed the following logic $array( 'pai1' => array( 'Filho1', 'Filho2' ), pai2 => array('Filho1', 'Filho2') ), I think it would look better than the logic described in your example above, so you do not need to go through the array, only put the parent and the corresponding parent number.

  • Yes @duque, but this form has already been implemented, I no longer have this option

  • So boy, this way you’ll be forced to go through the entire array searching for the indices without the underscore.

  • If you just need to get the indicies don’t need to loop. You will only need to get the information from such index.

1 answer

1

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

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

Well, that’s the general thing:

<?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!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.