如何使用foreach在PHP变量中提取数组数据?

时间:2013-02-07 07:04:17

标签: php

我需要提取最后一个数组数据,即SiteName,Url,Title到php中的变量。



array
  'ApplicableProductOfferings' => 
    array
      0 => string 'EasyDemo' (length=10)
  'Artist' => string 'Hello' (length=10)
  'ReferralDestinations' => 
    array
      0 => 
        array
          'SiteName' => string 'gettyimages' (length=11)
          'Url' => string 'http://www.gettyimages.com/detail/160414706' (length=43)
          'Title' => string 'Pixie Lott Launches The New BlackBerry Z10' (length=42)
          'UrlComp' => string 'http://localhost.com' (length=197)
          'UrlPreview' => string 'http://localhost.com' (length=164)
          'UrlThumb' => string 'http://localhost.com' (length=82)
          'UrlWatermarkComp' => string 'http://localhost.com' (length=197)
          'UrlWatermarkPreview' => string 'http://localhost.com

3 个答案:

答案 0 :(得分:0)

试试这个.......

   foreach($data as $dat)
   {
       foreach($dat['ReferralDestinations'] as $key => $d) 
        {
           echo $d['SiteName'];
           echo $d['Url'];
           echo $d['Title'];
        }
    }

答案 1 :(得分:0)

这取决于您如何在数组中存储数据。如果你有一个已经拥有最后一个数组数据的数组,那就很简单了。

foreach ($myArray as $var) {
  echo $var;
}

或以$ myArray ['SiteName'],$ myArray ['Url']等方式访问个别元素。

假设您在名为$ arrayOfArrays

的数组数组中包含上述数据
foreach ($arrayOfArrays as $myArray) {

  // $myArray now holds first array, second array etc as the loop is executed
  // First time it holds 'ApplicableProductOfferings', second time 'ReferralDesinations'..

  // If the array is 'ReferralDesitnations' you can loop through that array
  // to get the elements you are looking for SiteName etc as below

  foreach ($myArray as $URLElement) {
    echo $URLElement;
  }
}

答案 2 :(得分:0)

$array1 = [];
$array2 = [];

foreach ($array1 as $key=> $val) {
extract($array2, EXTR_IF_EXISTS, $val);
}

// extract()标志=> EXTR_IF_EXISTS ... // http://php.net/manual/ru/function.extract.php