[英]How to declare, insert and iterate a php associative array with an associative array as value?
I need to work with a hashtable which values can store variables like: 我需要使用哈希表,其值可以存储变量,如:
$numberOfItems
$ItemsNames
If I ain't wrong, that would mean another hash like array as value. 如果我没有错,那就意味着像数组一样的另一个哈希作为值。
What should be the right syntax for inserting and iterating over it? 插入和迭代它的正确语法应该是什么?
Is anything like: 是这样的:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
valid? 有效?
To create php array, which can be a hash table, you can do: 要创建可以是哈希表的php数组,您可以执行以下操作:
$arr['element'] = $item;
$arr['element'][] = $item;
$arr['element'][]['element'] = $item;
Other way: 另一种方式:
$arr = array('element' => array('element' => array(1)));
To iterate over it use foreach loop: 要迭代它,请使用foreach循环:
foreach ($items as $item) {
}
It's also possible to create nested loops. 也可以创建嵌套循环。
About your case: 关于你的案子:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
I would do: 我会做:
$hash['anyKey']['numberOfItems'] = 15;
$hash['anyKey']['ItemsNames'] = array('f','fw');
if there's no chance to have collusion in item name, you can use the name in key 如果项目名称中没有可能存在共谋,则可以在密钥中使用该名称
$hash[$ItemsName] = $numberOfItems;
in the other case, use an integer for example as a key, then the different "attributes" you want as keys for the 2nd array 在另一种情况下,使用整数作为键,然后使用不同的“属性”作为第二个数组的键
$hash[$integer]["count"] = $numberOfItems;
$hash[$integer]["name"] = $name;$
Then, for iterating (1st case): 然后,迭代(第一种情况):
foreach ($hash as $name => $number) {
echo $number;
echo $name;
}
or, 2nd case 或者,第二种情况
foreach ($hash as $item) {
echo $item["name"];
echo $item["count"];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.