如何创建简单的PHP数组?命名键和值


How to create simple PHP array? Name the key and the value

我正在尝试创建一个php数组,在这里我可以为每个条目存储2个变量,一个ID和VALUE。

比如,我有一些项目:

ID   VALUE
234  55.00
456  120.25
789  20.00

我正试图以某种方式将它们存储在一个数组中,以便稍后在页面上执行以下操作:

你买的:

'For each item in the array, echo ID, VALUE'

如何做到这一点?

像这个

<?php
$store = array(
  234 => 55,
  456 => 120.25,
  789 => 20
);
// call it like this
foreach($store as $id => $value) {
  echo 'Product with id ',$id,' has a value of ',$value,'$';
}

但在问这里之前,你应该做更多的研究!

可能是这样的吗?这也将允许您轻松地扩展数组,而不必重构代码。

$stuff = array(
    234 => array(
        'value' => 55.0
    ),
    456 => array(
        'value' => 120.25
    ),
    789 => array(
        'value' => 20.0
    )
);
foreach ($stuff as $id => $data) {
    echo "ID: $id, value: {$data['value']}<br>'n";
}

这是非常基本的东西。可能想花点时间读一本书或一些教程。。。

$items = array(
    234 => 55.00,
    456 => 120.25,
    789 => 20.00
    );
print "You Bought:<br />";
foreach( $items as $id => $cost )
{
    print "{$id}: {$cost}<br />";
}

http://codepad.org/vUHpJZMw

$arr[] = array(
            'id' => '1',
            'value' => 'abc'
     );
$arr[] = array(
            'id' => '2',
            'value' => 'efg'
     );
//.... etc
foreach($arr AS $r)
{
    echo $r['id'] . '=' . $r['value'];
}

只是一个例子。。