我对PHP和Laravel都是陌生的。我想从数组中转储特定信息。我宁愿不要使用foreach循环,因为我知道我想要的那个循环。
这是数组:
我想显示ICAR-中级
我尝试过:
dump($listofcarcodesnames[2]);
dump($listofcarcodesnames[2]['code']);
和
dump($listofcarcodesnames[2]->code);
和
dump($listofcarcodesnames->code[2]);
和
dump($listofcarcodesnames->$code[2]);
我确定这是我在语法中缺少的简单内容,但我无法弄清楚。如果不使用for循环遍历每个键和值,如何获得键ICAR和给定对值的代码部分?
**澄清:**
@ newUserName02和@Carlos Gurrero的以下两种回复都部分满足了我的需求
$listofcarcodesnames['ICAR']['CODE']->code;
如果我知道我正在寻找ICAR
,就可以使用,但是如果我只知道我需要第3位的信息,我将如何获得
$listofcarcodesnames[3rdKey]['CODE']->code;
答案 0 :(得分:0)
您必须通过键获取数组中的值。这是一个以字符串为键的关联数组,其中嵌套了一个对象。
您的示例的快速细分:
code
要访问其中的值,您可以执行以下操作:
// this will get you the value 'Intermediate'
dump($listofcarcodesnames['ICAR']['code']->code);
http://php.net/manual/en/language.types.array.php
注意:PHP允许您使用任何字符串或整数作为数组键,因此以下是一个非常有效的数组:
$array = [
0 => 'first index',
1 => 'second index',
'' => 'empty string key',
'anotherkey' => 'string key',
'nested' => [
'nested' => [
'nested' => 'etc'
],
0 => [
0 => 'hello',
1 => 'world',
],
],
];
dump($array[0]); // 'first index'
dump($array[1]); // 'second index'
dump($array['']); // 'empty string key'
dump($array['anotherkey']); // 'string key'
dump($array['nested']['nested']['nested']); // 'etc'
dump($array['nested'][0][0]); // 'hello'
至于获得“ ICAR”,取决于。由于它不是数组中的值,并且您已经知道这是您想要的特定内容,因此可以在需要的地方对其进行编码。
echo 'ICAR - ' . $listofcarcodesnames['ICAR']['code']->code;
编辑:如果您不知道确切的键名是什么,但是您碰巧知道它是第三个,则可以执行以下操作:
$count = 0;
foreach($listofcarcodesnames as $key => $val) {
if($count === 2) {
echo $key . ' - ' . $listofcarcodesnames[$key]['code']->code;
}
$count++;
}
但是请谨慎使用此方法。在PHP中时,关联数组中的键将保持相同的顺序。但是,如果要在PHP和JavaScript之间传递数据,则不保证JS对象的键具有一致的顺序。
答案 1 :(得分:0)
$listofcarcodesnames['ICAR']['CODE']->code;
应该给您“中级”
在Laravel Tinker中尝试过
php artisan tinker
Psy Shell v0.9.7 (PHP 7.2.0 — cli) by Justin Hileman
>>> $lisofcarcodesnames = []
=> []
>>> $lisofcarcodesnames['ICAR'] = []
=> []
>>> $lisofcarcodesnames['ICAR']['code'] = new stdClass
=> {#3041}
>>> $lisofcarcodesnames['ICAR']['code']->code = "Intermediate"
=> "Intermediate"
>>> echp json_encode($lisofcarcodesnames)
PHP Parse error: Syntax error, unexpected T_STRING on line 1
>>> echo json_encode($lisofcarcodesnames)
{"ICAR":{"code":{"code":"Intermediate"}}}⏎
>>> echo dump($lisofcarcodesnames)
array:1 [
"ICAR" => array:1 [
"code" => {#3041
+"code": "Intermediate"
}
]
]
ArrayPHP Notice: Array to string conversion in C:/Users/Charlie Guerreroeval()'d code on line 1
>>> echo $lisofcarcodesnames['ICAR']['code']->code
Intermediate⏎
>>>