【问题标题】:Loop through keys of an array, in order按顺序循环遍历数组的键
【发布时间】:2020-11-24 12:03:09
【问题描述】:

这很容易吗?

我有下一个代码:

for each_key in "${!myArray[@]}"
    do
        echo $each_key" : "${myArray[$each_key]}
    done

确定它工作正常,但项目没有按顺序显示

我试试

IFS=$'\n' orderedMyArray=($(sort <<< "${myArray[@]}"))
declare -p orderedMyArray

但给我的是价值而不是钥匙

【问题讨论】:

  • 不可能,关联数组条目本质上是无序的。所以你必须自己对它们进行排序。
  • $each_key" : "${myArray[$each_key]} 这很奇怪。只需引用它 - "$each_key : ${myArray[$each_key]}"

标签: arrays bash loops


【解决方案1】:

它的工作有缺陷,但项目没有按顺序显示

当然,按键排序是微不足道的——实际上只是按键排序。

for each_key in "${!myArray[@]}"; do
    echo "$each_key : ${myArray[$each_key]}" # remember to quote variable expansions!
done | sort

您可以在将键传递给for之前对其进行排序:

for each_key in "$(printf "%s\n" "${!myArray[@]}" | sort)"; do
# or funnier:
for each_key in $(IFS=$'\n'; sort <<<"${!myArray[*]}"); do
# or I think I would do a while read:
keys=$(IFS=$'\n'; sort <<<"${!myArray[*]}")
while IFS= read -r each_key; do ...; done <<<"$keys"

【讨论】:

  • 除非按顺序,他指的不是字母排序。我认为你是对的,但无论哪种方式都很容易。 :)
  • 非常感谢!!!,太好了,我会选择第二个选项,因为它最接近代码
  • 不知道为什么你“会做”而在 for-each-in-do ??
  • 无论你为什么建议引用变量表达式 [是的,我不喜欢 bash]
  • why you "would do" while over for-each-in-do ?? for i in $(...) 是一种反模式。阅读how to read a stream line by line in bashwhy you recommend to quote the variable expressions 防止分词扩展和文件名扩展。通常,当您看到$ 时,它应该在" 内。 quotes
【解决方案2】:

如果您的意思不是按字母顺序对键本身进行排序,您可以尝试使用并行数组。

$: order=( peach pear lemon lime ) # declare the order you want
$: declare -A data=( [peach]=pickled [pear]=salad [lemon]=drop [lime]=twist )
$: for k in "${order[@]}"; do echo "$k: ${data[$k]}"; done
peach: pickled
pear: salad
lemon: drop
lime: twist

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-10
    • 2015-11-21
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多