Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

php - 如何在PHP数组中访问不同的键和值(How to Access Different Keys and Values in a PHP Array)

I have this PHP array:

(我有这个PHP数组:)

Array
(
    [Album Title 1] => Array
        (
            [Track Title 1] => 27
            [Track Title 2] => 18
            [Track Title 3] => 7
        )

    [Album Title 2] => Array
        (
            [Track Title 1] => 41
            [Track Title 2] => 17
            [Track Title 3] => 12
        )

)

How can I echo "Album Title 1", "Track Title 1", and it's corresponding int(27), without using dot notation?

(如何在不使用点符号的情况下回显“专辑标题1”,“曲目标题1”及其对应的int(27)?)

(I don't know the exact title of "Album Title 1")

((我不知道“相册标题1”的确切标题))

To get "Album Title 1", I've tried:

(为了获得“专辑标题1”,我尝试过:)

echo $albums[0];

print_r(array_values($albums));

foreach ($albums as $a){
    print_r($a) . "
";
}

etc...

(等等...)

I've tried more variations of these for every value I need.

(对于我需要的每个值,我都尝试了这些的更多变化。)

  ask by Damien Stewart translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's not really good part of code, but should works:

(它不是代码的真正好部分,但是应该可以工作:)

$array = [
    'Album Title 1' => [
        'Track Title 1' => 27,
        'Track Title 2' => 18,
        'Track Title 3' => 7
    ]
];

$level1KeyName = array_keys($array)[0]; // Album Title 1
$level2KeyName = array_keys($array[$level1KeyName])[0]; // Track Title 1
$level2KeyValue = $array[$level1KeyName][$level2KeyName]; // 27

echo $level1KeyName . PHP_EOL;
echo $level2KeyName . PHP_EOL;
echo $level2KeyValue . PHP_EOL;

It prints:

(它打印:)

Album Title 1

(专辑标题1)

Track Title 1

(曲目标题1)

27

(27)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...