Reputation: 23
I have an array, where every item has a few parameters. One of the parameters is a hyperlink with the ID of that item. And I need that ID to be a key for that item value.
I've already tried something like this:
function item_preview($database)
{
foreach($database as $key=> $value)
{
$one= $key;
}
return $one;
}
$database= [
[
'name'=> 'item_one',
'img_src'=> 'pictures/item_one.jpg',
'preview_href'=> 'item_site.php?id='.item_preview($database).'',
'description'=> 'This product is.....' ,
],
[
'name'=> 'item_two',
'img_src'=> 'pictures/item_two.jpg',
'preview_href'=> 'item_site.php?id='.item_preview($database).'',
'description'=> 'This product is.....' ,
],
];
and what i need is...
$database= [
[
'name'=> 'item_one',
'img_src'=> 'pictures/item_one.jpg',
'preview_href'=> 'item_site.php?id= here should be key number',
'description'=> 'This product is.....' ,
],
[
'name'=> 'item_two',
'img_src'=> 'pictures/item_two.jpg',
'preview_href'=> 'item_site.php?id= here should be key number',
'description'=> 'This product is.....' ,
],
];
So I need id to be key of that item. So first item id=0; second item id=1;....
Upvotes: 1
Views: 64
Reputation: 692
You could do something like
$startingIndex = 0;
$database= [
[
'name'=> 'item_one',
'img_src'=> 'pictures/item_one.jpg',
'preview_href'=> 'item_site.php?id='.$startingIndex++.'',
'description'=> 'This product is.....' ,
],
[
'name'=> 'item_two',
'img_src'=> 'pictures/item_two.jpg',
'preview_href'=> 'item_site.php?id='.$startingIndex++.'',
'description'=> 'This product is.....' ,
],
That would result in id being 0
for the first entry, 1
for the second, and so on.
Upvotes: 2
Reputation: 78994
You can just define the key and use it in the href:
$database= [
0=>[
'name'=> 'item_one',
'img_src'=> 'pictures/item_one.jpg',
'preview_href'=> 'item_site.php?id=0',
'description'=> 'This product is.....' ,
],
1=>[
'name'=> 'item_two',
'img_src'=> 'pictures/item_two.jpg',
'preview_href'=> 'item_site.php?id=1',
'description'=> 'This product is.....' ,
]];
Or, after defining your array, just walk it and append the key:
$database= [
[
'name'=> 'item_one',
'img_src'=> 'pictures/item_one.jpg',
'preview_href'=> 'item_site.php?id=',
'description'=> 'This product is.....' ,
],
[
'name'=> 'item_two',
'img_src'=> 'pictures/item_two.jpg',
'preview_href'=> 'item_site.php?id=',
'description'=> 'This product is.....' ,
]];
array_walk($database, function(&$v, $k){ $v['preview_href'] .= $k; });
Upvotes: 0