循环遍历多维数组并一次从每个数组中提取数据1

时间:2014-03-27 00:35:06

标签: php arrays multidimensional-array

解析一些数据后,我有这个示例数组:

    array (
  0 => 
  array (
    0 => '3 1/2 cups peeled and diced potatoes',
    1 => '1/3 cup diced celery',
    2 => '1/3 cup finely chopped onion',
    3 => '2 tablespoons chicken bouillon granules',
    4 => '3 1/2 cups peeled and diced potatoes',
    5 => '1/3 cup diced celery',
    6 => '1/3 cup finely chopped onion',
    7 => '2 tablespoons chicken bouillon granules',
  ),
  1 => 
  array (
    0 => '3 1/2',
    1 => '1/3',
    2 => '1/3',
    3 => '2',
    4 => '3 1/2',
    5 => '1/3',
    6 => '1/3',
    7 => '2',
  ),
  2 => 
  array (
    0 => 'cup',
    1 => 'cup',
    2 => 'cup',
    3 => 'tablespoon',
    4 => 'cup',
    5 => 'cup',
    6 => 'cup',
    7 => 'tablespoon',
  ),
  3 => 
  array (
    0 => 'peeled and diced potatoes',
    1 => 'diced celery',
    2 => 'finely chopped onion',
    3 => 'chicken bouillon granules',
    4 => 'peeled and diced potatoes',
    5 => 'diced celery',
    6 => 'finely chopped onion',
    7 => 'chicken bouillon granules',
  ),
)   

不再需要第一个阵列了。数组1 - 3我需要循环并将结果存储在mySQL中,但是它们需要相互关联ala数组0.所以:

array1 0,array2 0,array3 0都属于一起 array1 1,array2 1,array3 1都属于一起 等

这是我完成此操作的代码:

//make sure there were matches found and if there were, organize the array
if(!empty($matches)) {
    $info_array = array();
    for ($i = 0; $i < count($matches); $i++) {
        for ($j = 1; $j < count($matches[$i]); $j++) {
            if ($j == 1) {
                $key = 'amount';
            }
            elseif ($j == 2) {
                $key = 'size';
            }
            elseif ($j == 3) {
                $key = 'ingredient';
            }
            $info_array[$i][$key] = $matches[$j][$i];
        }
    }

不幸的是,这不起作用。它产生了这个输出:

array (
  0 => 
  array (
    'amount' => '3 1/2',
    'size' => 'cup',
    'ingredient' => NULL,
  ),
  1 => 
  array (
    'amount' => '1/3',
    'size' => 'cup',
    'ingredient' => NULL,
  ),
  2 => 
  array (
    'amount' => '1/3',
    'size' => 'cup',
    'ingredient' => NULL,
  ),
  3 => 
  array (
    'amount' => '2',
    'size' => 'tablespoon',
    'ingredient' => NULL,
  ),
)

它只产生4个数组,我需要8. count($ matches)= 8,所以它运行第一个循环8次。我不知道我哪里出错了。有任何想法吗?非常感谢帮助!

1 个答案:

答案 0 :(得分:2)

通过以下代码替换您的循环代码

if(!empty($matches)) {
    $info_array = array();
    $total = count($matches[0]);
    for ($i = 0; $i < $total; $i++) {
        for ($j = 1; $j < count($matches); $j++) {
            if ($j == 1) {
               $key = 'amount';
            }
            elseif ($j == 2) {
                $key = 'size';
            }
            elseif ($j == 3) {
                $key = 'ingredient';
            }
            $info_array[$i][$key] = $matches[$j][$i];
        }
    }
}