拆分这个多维数组

时间:2014-01-21 00:39:16

标签: php arrays wordpress multidimensional-array

我如何分割这个数组来访问和循环浏览这些视频...

array(1) { 
[0]=> array(2) 
{ 

    [0]=> array(3) 
    { 
        ["title"]=> string(27) "A test title for this video" 
        ["video_item"]=> string(70) "http://dev.test/wp-content/uploads/2014/01/1.Introduction3.mp4" 
        ["video_image"]=> string(78) "http://dev.test/wp-content/uploads/2014/01/1.Introduction3_thumb23.jpg" 
    } 

    [1]=> array(3) 
    { 
        ["title"]=> string(13) "asdf fads fad" 
        ["video_item"]=> string(67) "http://dev.test/wp-content/uploads/2014/01/Spring-Mower.mp4" 
        ["video_image"]=> string(75) "http://dev.test/wp-content/uploads/2014/01/Spring-Mower1_thumb6.jpg" 
    } 

 }
} 

这是我正在使用的代码的一部分,但显然无法正常工作

// this gets the array 
$videos = get_post_meta( get_the_ID(), 'video_items', false );

$vid = array();
$img = array();
foreach( $videos as $video ) { 
    $vid[] = $video['video_item'];
    $img[] = $video['video_image'];

}

3 个答案:

答案 0 :(得分:2)

数组中有一个数组,所以在开始遍历每个数组之前需要访问第一个元素

所以只需在获得数组$videos = fullArray[0];

后添加此行
// this gets the array as you did in your original code block 
$fullArray = get_post_meta( get_the_ID(), 'video_items', false );

//But then you actually needed to add the below line. This gets the first 
//element of the array which happens to be an array and actually contains the array you 
//originally wanted to iterate through
$videos = fullArray[0];

$vid = array();
$img = array();

foreach( $videos as $video ) { 
    $vid[] = $video['video_item'];
    $img[] = $video['video_image'];
}

echo "video urls " . $vid . "\n";
echo "image urls " . $img;

答案 1 :(得分:0)

也许你可以使用array_chunk来获取它。

http://us2.php.net/manual/en/function.array-chunk.php

如文档中所述:

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>

将打印

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

答案 2 :(得分:0)

试试这个

foreach($array as $key => value)
{
     if(is_array($value))
     {
          foreach($value as $k => $v)ev
          {
                   foreach($v as $k1 => $v1)
                    {
                           echo $k1 .'=>'.$v1.PHP_EOL;
                    }
           }
     }
}

更好的是使用RecursiveIterator here