l2aelba
l2aelba

Reputation: 22197

Print custom array in custom pattern

If I have array looking like :

Array ( [date_type] => Date [date_text] => 20/12/2012 [place_type] => Place [place_text] => NY )

How can I print result like :

<span>Date</span><div>20/12/2012</div>
<span>Place</span><div>NY</div>
so on.... (if more custom array)

I came to this step now

$custom_info = array (
  "date_type" => "Date",
  "date_text" => "20/12/2012",
  "place_type"=>"Place",
  "place_text" => "NY" 
) ;
$count = count($custom_info)/2;

for ($i=1; $i<$count; $i++)
{

}

Someone can help me ?

Upvotes: 1

Views: 135

Answers (2)

dav
dav

Reputation: 9267

if your array always has the structure that you wrote, use this

    $i = 0;
    foreach ($custom_info as $k => $v) {
        if ($i % 2 == 0){
            echo "<span>".$v."</span>";
        } else {
            echo "<div>".$v."</div>";
        }

        $i++;
    }

tested

explanation:

according to your array structure, you should echo first element's value in span, and second element's value in div, and so on: $i % 2 == 0 shows that when it is element number 0, 2, 4 and so on, print in span, and if 1, 3, 5 and so on, print in div. a % b gives the remainder when you divide a on b

$i = 0,  $i % 2 --> 0
$i = 1,  $i % 2 --> 1
$i = 2,  $i % 2 --> 0
$i = 3,  $i % 2 --> 1
$i = 4,  $i % 2 --> 0

Upvotes: 4

Vyktor
Vyktor

Reputation: 21007

Using foreach, explode() and ucfirst():

foreach( $custom_info as $k => $v){
    $parts = explode( '_', $k);
    if( count($parts) != 2){
       throw new Exception( 'Invalid format of key: ' . $k);
    }

    if( $parts[1] != 'text'){
       continue;
    }

    // Build label
    $key = $parts[0] . '_type';
    $label = '';
    if( isset( $custom_info[ $key])){
        $label = $custom_info[ $key];
    } else {
        $label = ucfirst( $parts[0]);
    }

    echo '<span>' . htmlspecialchars( $label) . '</span><div>' 
         . htmlspecialchars( $v) . '</div>';
}

Or you could replace explode() by function like this (which will support also long_key_text, using strrpos()):

function getParts( $key){
    $pos = strrpos( $key, '_');
    if( $pos === false){
        return false; // or array or so
    }

    return array(
        substr( $key, 0, $pos),
        sbustr( $key, $pos+1)
    );
}

Based on Elbys comment and your answer the simplest way how to do this would be:

$custom_info = array (
  "Date" => "20/12/2012",
  "Place" => "NY" 
) ;

foreach( $custom_info as $k => $v){
    echo '<span>' . htmlspecialchars( $k) . '</span><div>' 
         . htmlspecialchars( $v) . '</div>';
}

Upvotes: 2

Related Questions