簡體   English   中英

使用PHP在多維數組Whiteout循環中輸出數據

[英]Output datas from a multidimensional array whiteout looping in it with PHP

我有這種類型的數組結構:

$fruits = array(
    array(
        'name'      => 'Banana',
        'continent' => 'Africa', 
        'counts'    => array(
            'standard'  => 15,
            'advanced'  => 20
        )
    ),
    array(
        'name'      => 'Apple',
        'continent' => 'Europa', 
        'counts'    => array(
            'standard'  => 25,
            'advanced'  => 25
        )
    )
);

如何在不循環的情況下(foreach)從該數組輸出一個數據?

例如,我想這樣寫:在Europa ,我可以找到25 standard Apple

所以我嘗試了一下,沒有任何結果:

<?
    echo 'In ';
    echo $fruits['name']['Banana']=>'continent';
    echo ', I can find ';
    ...
    echo '.'.
?>

通過將嵌套的數組變量包裝在大括號中來進行類似嘗試{} 在此處查看更多

<?php
$fruits = array(
    array(
        'name'      => 'Banana',
        'continent' => 'Africa', 
        'counts'    => array(
            'standard'  => 15,
            'advanced'  => 20
        )
    ),
    array(
        'name'      => 'Apple',
        'continent' => 'Europa', 
        'counts'    => array(
            'standard'  => 25,
            'advanced'  => 25
        )
    )
);
//In Europa, I can find 25 standard Apple.
$key = array_keys($fruits[1]['counts'])[0];
echo "In {$fruits[1]['continent']}, I can find {$fruits[1]['counts']['standard']} {$key} {$fruits[1]['name']}";
?>

演示: https : //3v4l.org/KoQiO

如果您知道結果數據索引,那么您可以獲得沒有循環的單個記錄的輸出。

但是,如果您希望打印整個記錄,那么for-each應該是必須的。 以下代碼是您當前的記錄。

echo 'In ' . $fruits[1]["continent"] . ', I can find ' . $fruits[1]["counts"]["standard"] . ' standard ' . $fruits[1]["name"] . '.';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM