PHP,数组迭代

时间:2013-11-19 12:28:43

标签: php arrays

我有这个数组结构:

$ar = [product_info] => Array
                (
                    [pname] => Array
                        (
                            [0] => Выделенный сервер DE-22
                            [1] => Hello 4
                            [2] => Hello World
                        )

                    [pid] => Array
                        (
                            [0] => 217
                            [1] => 342
                            [2] => 343
                        )

我想像这样迭代它(在一个循环中):

foreach ($ar['product_info'] as $item) {
   echo $item['pname'];
   echo $item['pid']
}

我该怎么做?需要帮助

3 个答案:

答案 0 :(得分:1)

我认为解决它是正常的。

$total = count($ar['product_info']['pid']);
for($i=0; $i<$total; $i++){
  echo $ar['product_info']['pname'][$i];
  echo $ar['product_info']['pid'][$i];
}

答案 1 :(得分:0)

您需要迭代内部数组,这些数组是int-indexed:

$size=sizeof($ar['product_info']['pname'];
for ($i=0;$i<$size;$i++) {
   echo $ar['product_info']['pname'][$i];
   echo $ar['product_info']['pid'][$i];
}

答案 2 :(得分:0)

<?php

$ar = array(
    'product_info' => array(
        'pname' => array(
            'Product 1',
            'Product 2',
            'Product 3',
            'Product 4 > test <',
        ),
        'pid' => array(
            217,
            342,
            343,
            666,
        ),
    ),
);

foreach($ar['product_info']['pid'] as $productIndex => $productId)
{
    $productName = $ar['product_info']['pname'][$productIndex];
    echo '<a href="?product_id=' . intval($productId) . '">';
    echo htmlspecialchars($productName);
    echo '</a>';
    echo '<br />' . PHP_EOL;
}