0

I have this code:

$arr = json_decode($jsondata, TRUE);
$arr2 = $arr['items']['item'];
echo '<ul>';
foreach ($arr2 as $val) {
echo '<li>'.$val[description].'</li>';
}
echo '</ul>';

Which outputs:

  • Ann (24/05/2014 - 23/05/2015)
  • Late Fee (Added 18/05/2014)

I just want to store 'Ann' in a variable say $plan. I cant seem to get this done. How can I do this?

2 Answers2

0

First up, I would clean up the PHP code a bit. You should never write plain HTML inside PHP.

<?php
$arr = json_decode($jsondata, TRUE);
$arr2 = $arr['items']['item'];
?>
<ul>
    <?php foreach ($arr2 as $val): ?>
    <?php $plan = explode('(', $val[description])[0] ?>
    <li><?php echo $val[description] ?></li>
    <?php endforeach ?>
</ul>

With explode('(', $val[description])[0]) you get the first part before (. $plan would cointian Ann and after the first iteration Late Fee.

RHB
  • 102
  • 2
  • 11
  • Thanks for your help but this didn't fixed it, i've tried this before. I dont want the Late Fee part. Anyways, I got my fix. – user3672357 May 24 '14 at 19:30
0

I think you want to get everything before the first "(". This is not necessarily the first 3 characters.

function get_everything_before_paren_open($str)
{
    $p = strpos($str, '(');
    if($p === FALSE) {
        return $p;
    } else {
        return rtrim(substr($str, $p-1));
    }
}

Then you can write your code as

$arr = json_decode($jsondata, TRUE);
$arr2 = $arr['items']['item'];
echo '<ul>';
foreach ($arr2 as $val) {
    $plan = get_everything_before_paren_open($val["description"]);
    echo '<li>'.$plan.'</li>';
    // Position 1
}
echo '</ul>';

This will output

  • Ann
  • Late Fee

If you want to just output "Ann", just add a break; into the code instead of // Position 1. Then "Ann" will be placed into $plan.

BTW, you should quote "description".

Michael
  • 6,451
  • 5
  • 31
  • 53