PHP foreach与嵌套数组?[副本]

8dtrkrch  于 2023-05-05  发布在  PHP
关注(0)|答案(5)|浏览(209)

此问题已在此处有答案

Is there a function to extract a 'column' from an array in PHP?(15个回答)
昨天关门了。
我有一个嵌套数组,我想在其中显示结果的子集。例如,在下面的数组中,我想循环遍历嵌套数组[1]中的所有值。

Array
(
  [0] => Array
    (
      [0] => one
      [1] => Array
        (
          [0] => 1
          [1] => 2
          [2] => 3
        )
    )

  [1] => Array
    (
      [0] => two
      [1] => Array
        (
          [0] => 4
          [1] => 5
          [2] => 6
        )
    )

  [2] => Array
    (
      [0] => three
      [1] => Array
        (
          [0] => 7
          [1] => 8
          [2] => 9
        )
    )
)

我试图使用foreach函数,但我似乎不能让这个工作。这是我最初的语法(尽管我意识到它是错误的)。

$tmpArray = array(array("one",array(1,2,3)),array("two",array(4,5,6)),array("three",array(7,8,9)));

foreach ($tmpArray[1] as $value) {
  echo $value;
}

我试图避免一个变量比较的关键是否是相同的关键,我想搜索,即。

foreach ($tmpArray as $key => $value) {
  if ($key == 1) {
    echo $value;
  }
}

有什么想法吗

1zmg4dgp

1zmg4dgp1#

如果你知道嵌套数组的层数,你可以简单地做嵌套循环。就像这样:

//  Scan through outer loop
foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

如果你不知道数组的深度,你需要使用递归。参见以下示例:

//  Multi-dementional Source Array
$tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(
            7,
            8,
            array("four", 9, 10)
    ))
);

//  Output array
displayArrayRecursively($tmpArray);

/**
 * Recursive function to display members of array with indentation
 *
 * @param array $arr Array to process
 * @param string $indent indentation string
 */
function displayArrayRecursively($arr, $indent='') {
    if ($arr) {
        foreach ($arr as $value) {
            if (is_array($value)) {
                //
                displayArrayRecursively($value, $indent . '--');
            } else {
                //  Output
                echo "$indent $value \n";
            }
        }
    }
}

下面的代码仅显示嵌套数组,其中包含特定情况下的值(仅限第3级)

$tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(7, 8, 9))
);

//  Scan through outer loop
foreach ($tmpArray as $inner) {

    //  Check type
    if (is_array($inner)) {
        //  Scan through inner loop
        foreach ($inner[1] as $value) {
           echo "$value \n";
        }
    }
}
dgiusagp

dgiusagp2#

foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}
xmjla07d

xmjla07d3#

两种语法都是正确的。但结果是Array。你可能想做这样的事情:

foreach ($tmpArray[1] as $value) {
  echo $value[0];
  foreach($value[1] as $val){
    echo $val;
  }
}

这将打印出字符串“two”($value[0])和数组($value[1])中的整数4、5和6。

nhaq1z21

nhaq1z214#

据我所知,所有以前的答案,不使数组输出,在我的情况下:我有一个父子结构的模型(这里有简化的代码):

public function parent(){

    return $this->belongsTo('App\Models\Accounting\accounting_coding', 'parent_id');
}

public function children()
{

    return $this->hasMany('App\Models\Accounting\accounting_coding', 'parent_id');
}

如果你想让所有的子ID都作为一个数组,这种方法很好,对我来说很有效:

public function allChildren()
{
    $allChildren = [];
    if ($this->has_branch) {

        foreach ($this->children as $child) {

            $subChildren = $child->allChildren();

            if (count($subChildren) == 1) {
                $allChildren  [] = $subChildren[0];
            } else if (count($subChildren) > 1) {
                $allChildren += $subChildren;
            }
        }
    }
    $allChildren  [] = $this->id;//adds self Id to children Id list

    return $allChildren; 
}

allChildren()返回一个简单的数组。

bbuxkriu

bbuxkriu5#

我有一个嵌套的值数组,需要确保这些值都不包含&,所以我创建了一个递归函数。

function escape($value)
{
    // return result for non-arrays
    if (!is_array($value)) {
        return str_replace('&', '&', $value);
    }

    // here we handle arrays
    foreach ($value as $key => $item) {
        $value[$key] = escape($item);
    }
    return $value;
}

// example usage
$array = ['A' => '&', 'B' => 'Test'];
$result = escape($array);
print_r($result);

// $result: ['A' => '&', 'B' => 'Test'];

相关问题