【发布时间】:2017-01-19 13:50:52
【问题描述】:
编辑1:关于Multi-dimensional arrays in Bash,据我所知,所有答案和示例都是关于关联数组,而不是像下面的数字多维数组。他们只使用 ONE 值命名索引,而不是具有超过 ONE 值的数字索引。
编辑 2:根据this answer,也许不可能在 Bash 中做我想做的事情,因为我不能做类似的事情:echo $A[1][1] 来获取数组中第二个索引的第二个值,就像我们一样通常可以在 PHP 和其他中。
编辑 3:根据this other question,我几乎可以肯定这不能在 Bash 中以“人类可读”的方式完成。
在 PHP 中,这是创建数字多维数组的方式:
<?php
$b[]=array("Apple's Mac","UNIX from Ken, Dennis, Douglas and Peter");
$b[]=array("Sun Microsystems' Solaris","Linus Torvalds' Linux");
//or:
$b=array(
array("Apple's Mac","UNIX from Ken, Dennis, Douglas and Peter"),
array("Sun Microsystems' Solaris","Linus Torvalds' Linux")
);
print_r($b);
/*Array
(
[0] => Array
(
[0] => Apple's Mac
[1] => UNIX from Ken, Dennis, Douglas and Peter
)
[1] => Array
(
[0] => Sun Microsystems' Solaris
[1] => Linus Torvalds' Linux
)
)*/
//To access the first numeric array:
print_r($b[0]);
?>
我怎样才能在 Bash 中做到这一点?这是我迄今为止尝试过的:
A=(
"Apple's Mac" "UNIX from Ken, Dennis, Douglas and Peter"
"Sun Microsystems' Solaris" "Linus Torvalds' Linux"
)
#Trying to print the second array inside array ${A[@]}...
echo ${A[1]}
#It prints:
UNIX from Ken, Dennis, Douglas and Peter
#The same if I do:
X=("Apple's Mac" "UNIX from Ken, Dennis, Douglas and Peter")
Y=("Sun Microsystems' Solaris" "Linus Torvalds' Linux")
A=(
"${X[@]}"
"${Y[@]}"
)
echo ${A[1]}
#It prints:
UNIX from Ken, Dennis, Douglas and Peter
我能找到得到我想要的唯一“hackish”方式:
A=(
"Apple's Mac|UNIX from Ken, Dennis, Douglas and Peter"
"Sun Microsystems' Solaris|Linus Torvalds' Linux"
)
#Printing the second index of the array
echo ${A[1]}
#It prints:
Sun Microsystems' Solaris|Linus Torvalds' Linux
#Accessing the second "value" of the second index
echo ${A[1]} | cut -d'|' -f2
#It prints:
Linus Torvalds' Linux
但必须有一种更简单、更正确、正确的方法来做同样的事情......
感谢您的帮助。
【问题讨论】:
-
是的,
A会变成一个包含X和Y内容的多元素数组,其第二个元素是您打印的那个 -
是的,但这与我想要的不同。 bash 数组的第二个索引必须是一个数组,和我从 PHP 代码中得到的一样。
-
正如我上面所说:“据我所知,所有的答案和示例都是关于关联数组,而不是像下面的数字多维数组。他们命名的索引只有一个值,而不是具有多个值的数字索引。"
标签: php arrays bash multidimensional-array