简体   繁体   中英

How to extract array data in PHP variable with foreach?

I need to extract last array data ie SiteName, Url, Title to the variable in 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

try this.......

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

It depends on how you are storing the data in the array. If you have an array that already has the last array data, it's very simple.

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

or access individual elements as $myArray['SiteName'], $myArray['Url'] etc..

Assuming you have the above data in an array of arrays called $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;
  }
}
$array1 = [];
$array2 = [];

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM