1

I have the following array structure;

Array(
[0] => Array(
        [product_name] => Silver
    )

[1] => Array(
        [product_name] => Gold
    )

[2] => Array(
        [product_name] => Ride
    )

[3] => Array(
        [product_name] => Bronze
    )
)

I need it to be like this, but I can't figure out how. I can't implement an additional function, it needs to be clean and neat.

Array(
    [0] => Silver
    [1] => Gold
    [2] => Ride
    [3] => Bronze
)

Thanks for any help offered. :)

6 Answers 6

2

I believe this works:

iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)), false);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks alix. I've no idea what this is doing, but the code I'm working in is very OOP, so this seems more in keeping with that style. Thanks.
2
foreach($array as &$value)
{
    $value = $value['product_name'];
}

1 Comment

Your solution is probably the simplest. But I suggest unset $value; afterwards to avoid problems if you reuse the variable name.
2

I'd use array_map personnaly !

$array = array_map(function($product){return $product['product_name'];}, $array);

Comments

1

If [product_name] is the key name, then this would work:

foreach($array as $i=>$a)
    $array[$i] = $a['product_name'];

Comments

1
foreach($firstarray as $var) {
   $secondarray[] = $var["product_name"];
}

1 Comment

Can't you just drop the $i and use $secondarray[] = $var["product_name"];?
0
$array = array(
    array("product_name" => "Silver"),
    array("product_name" => "Gold"),
    array("product_name" => "Ride"),
    array("product_name" => "Bronze")
);

You can do somenthing like this:

foreach($array as &$pos) $pos = $pos["product_name"];

So if you do a print_r($array) the result will be:

Array
(
    [0] => Silver
    [1] => Gold
    [2] => Ride
    [3] => Bronze
)

Hope this help you.

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.