2

I have an multidimensional array that follows certain pattern but 'x' element is always different?

This is a pattern:

$category['children'][x]['alias'] 

How to bypass 'x' and get that values?

3
  • 1
    Get what value? Are there many different x's? Commented Jun 28, 2017 at 17:51
  • Do you want the 'alias' value for all the x's or just a specific one? Commented Jun 28, 2017 at 17:51
  • 1
    foreach($category['children'] as $x) { foreach($x as $alias) { //code here using $alias; }}? Loops through each x to get its values? Not sure the full context or usage Commented Jun 28, 2017 at 17:54

4 Answers 4

4

You can also extract all of the alias columns if that is the only one you are concerned with:

$aliases = array_column($category['children'], 'alias');

If you just want the first one:

$alias = reset($category['children'])['alias'];
Sign up to request clarification or add additional context in comments.

4 Comments

I like your answer, however, using reset makes an assumption that isn't necessarily true. It will only work if the first element of $category['children'] is an array with an 'alias' element. We don't know whether that is true given the question. Also array_column was introduced in php 5.5, so it's relatively new.
Yes we must assume when the question doesn't stipulate much, but as for 5.5, it's 4 years old and support ended 1 year ago.
Good point on 5.5. Personally, I think your answer is the best one provided, and works even if the array won't work with the reset() based solution.
Sorry for not providing enough information about what I wanted, yet you still managed to figure it out, Thanks, your post answers my question.
2
$children = $category['children'];
$x        = array_pop($children);
$theValue = $children['alias'];

This assumes a few things, you have not provided in your question.

1 Comment

Works, but only if every element in $category['children'] is an array with an 'aiias' key in it. We don't know from the question unfortunately.
0

You can get all keys of an array using array_keys

$current = array_keys($category['children']);

$value = $category["children"][$current[0]]["alias"]; 

This code will get the value of index alias in the first item in the sub array "children".

1 Comment

You have the same flaw as several other solutions, in that this doesn't work if the first element of the $category['children'] array, doesn't have an 'alias' key member.
0

If you want to get all the 'alias' values for all x's, then you can just loop through them:

$alias = new array();
foreach($category['children'] as $x) {
  $alias[] = $x['alias'];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.