Page 1 of 1
[SOLVED] array - printing key and value
Posted: Thu Oct 26, 2006 8:10 am
by malcolmboston
i have this array
Code: Select all
Array
(
[Silas] => 20
[OTS] => 1
[MK Yen] => 1
[Carhartt] => 1
[Marshall Artist] => 1
)
now i need to print
Silas: 20
OTS: 1
in this format however no matter what i do, its just not working, can someone prod me in the right direction please?
Posted: Thu Oct 26, 2006 8:14 am
by feyd
Code?
Posted: Thu Oct 26, 2006 8:17 am
by malcolmboston
Code: Select all
$c =1;
foreach ($newStockArray as $v) {
echo ''.$newStockArray[$c].' => '.$v.'';
$c++;
}
i dont usually hold arrays like this, ive never used foreach and the manual for that page is sketchy at best
Posted: Thu Oct 26, 2006 8:25 am
by feyd
Okay, so $newStockArray is the array output above?
$newStockArray['Sila'] and $newStockArray['OTS'] would be the references to use, not numeric indexing. Now, if $v is the above array the references would be very similar, and one could use
Code: Select all
foreach($newStockArray as $c => $v)
{
echo $v['Sila'];
}
for example.
Posted: Thu Oct 26, 2006 8:29 am
by malcolmboston
this is basically a for loop, so would i need to do array_keys and then echo the key dynamically?
Posted: Thu Oct 26, 2006 8:36 am
by malcolmboston
NvM
Code: Select all
$newStockKeys = array_keys ($newStockArray);
$c = 0;
foreach ($newStockArray as $v) {
// get percentage
$percentageBrand = number_format((($v / $totalItems) * 100), 2);
echo ''.$newStockKeys[$c].': '.$v.' <strong>'.$percentageBrand.'%</strong><br>';
$c++;
}
it just seems like a really long way of doing something that should be so simple :S
Posted: Thu Oct 26, 2006 8:39 am
by volka
Code: Select all
<?php
$a = array(
'Silas' => 20,
'OTS' => 1,
'MK Yen' => 1,
'Carhartt' => 1,
'Marshall Artist' => 1,
);
foreach($a as $i=>$v) {
echo $i, ': ', $v, "<br />\n";
}
?>