我在Yii中有一个数组 - 如何打印数组元素?

时间:2022-01-09 20:47:17
$departmentServiceData = Yii::app()->session->get('branch_service');

CUtil::printArray($departmentServiceData);

I got this array.

我有这个阵列。

Array
(
[0] => Array
    (
        [1] => Array
            (
                [0] => s11
                [1] => s12
            )

    )

[1] => Array
    (
        [2] => Array
            (
                [0] => s21
                [1] => s22
                [2] => s23
            )

    )

)

How do I print this array element?

如何打印此数组元素?

1 个解决方案

#1


It depends how you're using the array and the elements within it.

这取决于您如何使用数组及其中的元素。

If you know your array keys, you could access the values directly:

如果您知道数组键,则可以直接访问这些值:

print $departmentServiceData[0][1][0]; // s11
print $departmentServiceData[1][2][2]; // s23

Alternatively, you can use a foreach and loop each of the nested arrays until you can print the values:

或者,您可以使用foreach并循环每个嵌套数组,直到您可以打印值:

foreach($departmentServiceData as $k1 => $array1)
{
    print 'key 1: ' . $k1 . '<br>';

    foreach($array1 as $k2 => $array2)
    {
        print 'key 2:' . $k2 . '<br>';

        foreach($array2 as $k3 => $value)
        {
            print 'key 3:' . $k3 . '<br>';

            print '<strong>Value is:' . $value . '</strong><br />';
        }
    }
}

#1


It depends how you're using the array and the elements within it.

这取决于您如何使用数组及其中的元素。

If you know your array keys, you could access the values directly:

如果您知道数组键,则可以直接访问这些值:

print $departmentServiceData[0][1][0]; // s11
print $departmentServiceData[1][2][2]; // s23

Alternatively, you can use a foreach and loop each of the nested arrays until you can print the values:

或者,您可以使用foreach并循环每个嵌套数组,直到您可以打印值:

foreach($departmentServiceData as $k1 => $array1)
{
    print 'key 1: ' . $k1 . '<br>';

    foreach($array1 as $k2 => $array2)
    {
        print 'key 2:' . $k2 . '<br>';

        foreach($array2 as $k3 => $value)
        {
            print 'key 3:' . $k3 . '<br>';

            print '<strong>Value is:' . $value . '</strong><br />';
        }
    }
}