【问题标题】:Numeric Multidimensional Array (AKA 2D-Array or Bidimensional Array) - Bash数值多维数组(AKA 2D 数组或二维数组) - Bash
【发布时间】: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


【解决方案1】:

不是最好的,但这是另一种解决方案:

你可以像下面这样使用声明

#!/bin/bash

A1=("Apple's Mac" "UNIX from Ken, Dennis, Douglas and Peter")
A2=("Sun Microsystems' Solaris" "Linus Torvalds' Linux")

declare -p A1 A2 > multi-array.save

如果您需要重新加载不同的数组:

source ./multi-array.save

当然,这不是多维的,但为了记忆,它得到了类似的东西。

【讨论】:

  • 请问,如何通过您的解决方案访问“Linus Torvalds' Linux”的值?
猜你喜欢
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 2014-04-30
  • 1970-01-01
  • 2017-02-19
  • 2015-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多