【问题标题】:display each item in the array without using a loop [closed]在不使用循环的情况下显示数组中的每个项目[关闭]
【发布时间】:2014-07-31 05:30:29
【问题描述】:

嗨,我有这个特定的 php 函数。但我无法弄清楚如何输出这个。这是问题 // 给定一个数组,在不使用循环的情况下显示数组中的每个项目。 (不要使用内置函数来执行此操作,例如 PHP 的 print_r;使用递归函数来实现) 这是代码

<?php
  function print_array(array $input)
  {
  }
?>

有人可以分享这方面的想法吗?非常感谢任何帮助。

【问题讨论】:

  • 这不是家庭作业服务。它也不是回答面试问题的服务(面试的重点是确定你是否合格——如果你需要我们做,你不是)。

标签: php arrays


【解决方案1】:

你可以使用implode

$your_array = array("abc", "5", "xyz")

$text  = implode(" ", $your_array); // implode with space you can use any other on this place

echo $text;

输出: abc 5 xyz

功能:

function print_array($your_array)
{
   $text  = implode(" ", $your_array); // implode with space you can use any other on this place

    echo $text;
}

递归法:

但仅在数组的键为以 0, 1, 2 .... 开头的数字时使用。

print_array($your_array);

function print_array($your_array, $index=0)
{   
    if(isset($your_array[$index]))
    {
        echo $your_array[$index]; 
        $index+=1;
        print_array($your_array, $index)
    }   
}

【讨论】:

  • $your_array = array("a"=>"x1", "b"=>"x2", "c"=>"x3");当数组是这样的时候,你的代码是否有效!
  • 但是使用函数 print_array(array $input){ } 就可以了...
  • implode 是内置函数吗?
  • @user3717576 将此代码放入您的函数中
  • 不要使用内置函数使用递归函数来实现
猜你喜欢
  • 2013-05-19
  • 2019-08-14
  • 1970-01-01
  • 1970-01-01
  • 2021-05-03
  • 2022-01-14
  • 2014-11-12
  • 2018-06-02
  • 2018-02-20
相关资源
最近更新 更多