Page 1 of 1

Array Keys and how do I get them?

Posted: Sun Oct 14, 2012 8:20 pm
by Temor
I have this array setup:
          Array
(
    [cart] => Array
        (
            [0] => Array
                (
                    [item_id] => 1
                    [item_name] => item name
                    [price] => 2
                    [quantity] => 5
                )

            [1] => Array
                (
                    [item_id] => 3
                    [item_name] => another item name
                    [price] => 1
                    [quantity] => 76
                )

            [2] => Array
                (
                    [item_id] => 5
                    [item_name] => yet another item name
                    [price] => 3
                    [quantity] => 9
                )

        )

)
The cart array contains an array for every item inside the cart. What I want is the array key for each item. This is where I'm stuck.

This is probably just me being slow after not writing any code for at least a month, but any guidance is appreciated :)

Re: Array Keys and how do I get them?

Posted: Sun Oct 14, 2012 8:34 pm
by EcazS
http://php.net/manual/en/function.array-keys.php

Maybe?
Not sure if that function works in "multiple dimensions" though, hmm..

Re: Array Keys and how do I get them?

Posted: Sun Oct 14, 2012 11:32 pm
by Temor
array_keys will return the value of item_id. I want it to go up one level.

Re: Array Keys and how do I get them?

Posted: Sun Oct 14, 2012 11:44 pm
by EcazS
So, if I understand this correctly you want (from your example) 0, 1 and 2?

Re: Array Keys and how do I get them?

Posted: Mon Oct 15, 2012 5:20 am
by Temor
yes. precisely

Re: Array Keys and how do I get them?

Posted: Mon Oct 15, 2012 5:30 am
by EcazS
Well, I suppose if the array will always be called "cart" you could do something like this.
Hopefully I replicated your array correctly,
$array = array(
	"cart"	=> array(
		"0"	=>	array(
			"item_id"	=> "1",
			"item_name"	=> "item name",
			"price"	=> "2",
			"quantity"	=> "5"
		),
		"1"	=>	array(
			"item_id"	=> "3",
			"item_name"	=> "another item name",
			"price"	=> "1",
			"quantity"	=> "76"
		),
		"2"	=>	array(
			"item_id"	=> "5",
			"item_name"	=> "yet another item name",
			"price"	=> "3",
			"quantity"	=> "9"
		)
	)
);

echo "<pre>" . print_r(array_keys($array["cart"]), true) . "</pre>";
This returns an array that looks like this,
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
)

Re: Array Keys and how do I get them?

Posted: Mon Oct 15, 2012 4:30 pm
by Temor
Works wonders. Thank you :)