开发者

Query regarding associative arrays PHP

I have a question about associative arrays in php.

I have following array in which there are two items named 4 and 2 respectively.

$items = array(4,2);

Now i want to associate each item's quantity to it which can be done as follows:

$items['4']=23;
$items['2']=0;

which means that there are 23, 'item 4s' and no 'item 2'.

But I sometimes don't know in advance what is there in the $items so i want to associate quantity on basis of location. I wanted to do something like associate 23 to whatever is there on the zero location of the item array:

$items['items[0]']=23;

This of course did not work because its not the rig开发者_StackOverflow中文版ht way to extract whatever is placed on the zero location of items. Can anyone please tell me how do i do that?


You are confusing in the use of item and items. I imagine you have both an item array and an items array, else things can easily get hairy.

Anyhow, you just refer to it as a variable, not as a string:

$items[$item[0]] = 23;


Let me get this straight. So you start with an array that looks like this:

$items = array( 0 => 4, 1 => 2 )

And you want to end up with an array that looks like this: ?!

$items = array( 0 => 4, 1 => 2, 2 => 0, 4 => 23 )


I think you should use your array as a kind of "map". The item number is your key, and the quantity your value.

By calling

$items = array(4,2);

you create

$items[0] = 4;
$items[1] = 2;

but you want to use the 4 and 2 as a key in your array. So you should instead use

$items = array( 4 => false, 2 => false );

where false stands for an item that has not yet a quantity associated (could also be e.g. -1). This creates

$items[2] = false;
$items[4] = false;

When using false, you can check for not assigned values by calling

if ($items[4] === false) {
  echo "No quantity set!";
}

And now the second step.. if you want to assign the item #4 a quantity of 23, just call

$items[4] = 23;

So I don't think you will want to rely on the order inside your array..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜