简体   繁体   English

打印数组,无任何循环或递归

[英]Printing Array without any loop or recursion

有没有一种方法可以在没有任何循环或递归的情况下在php中打印数组?

You could try print_r($array); 您可以尝试print_r($ array); or var_dump($array); var_dump($ array); to display key/value information about the array. 显示有关数组的键/值信息。 This is used mainly for debugging. 这主要用于调试。

Alternatively if you want to display the array to users, you can use implode to stick the elements together with custom "glue", implode(' ',$array); 或者,如果要向用户显示数组,则可以使用implode将元素与自定义“ glue”, implode('',$ array);粘贴在一起 .

print_r是您要寻找的功能。

Depends on what you want. 取决于您想要什么。

print_r() prints human-readable information about a variable but var_dump() displays structured information about expressions that includes its type and value. print_r()打印有关变量的人类可读信息,但是var_dump()显示有关表达式的结构化信息,包括其类型和值。

It depends on your wanted result. 这取决于您想要的结果。 You could use several functions for different purposes. 您可以将几个功能用于不同的目的。

Here are some examples: 这里有些例子:

You can use print_r for debug output. 您可以将print_r用于调试输出。

<?php
    $a = array ('a' => 'Apfel', 'b' => 'Banane', 'c' => array ('x', 'y', 'z'));
    print_r ($a);
?>

... will produce ...将产生

Array
(
    [a] => Apfel
    [b] => Banane
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)

If you need some specific formated result/output you could use array_walk 如果您需要某些特定格式的结果/输出,可以使用array_walk

<?php
$fruits = array("d" => "Zitrone", "a" => "Orange", "b" => "Banane", "c" => "Apfel");

function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2<br>\n";
}

array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'Frucht');

array_walk($fruits, 'test_print');
?>

... will produce ...将产生

d. Zitrone
a. Orange
b. Banane
c. Apfel

d. Frucht: Zitrone
a. Frucht: Orange
b. Frucht: Banane
c. Frucht: Apfel

An even more generic way might be iterator_apply 更为通用的方法可能是iterator_apply

<?php
function print_caps(Iterator $iterator) {
    echo strtoupper($iterator->current()) . "\n";
    return TRUE;
}

$it = new ArrayIterator(array("Apples", "Bananas", "Cherries"));
iterator_apply($it, "print_caps", array($it));
?>

... will produce ...将产生

APPLES
BANANAS
CHERRIES

But in the end... they are all loop through the array internally, of course. 但是最后,它们当然都是内部遍历数组。 There are many other functions (eg array_map ) that might be the right choice for your coding... have a look at the documentation of php and search for array functions . 还有许多其他函数(例如array_map )可能是您进行编码的正确选择...查看php文档并搜索数组函数

function num($a,$b){

    if($b<0)
    {
        return false;

    }
    else
    {
        echo $a * $b;

        num($a,--$b);
    }
}

$a=1;
$b=5;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM