Showing posts with label PHP Select Array Based on value. Show all posts
Showing posts with label PHP Select Array Based on value. Show all posts

Friday, 19 September 2014

PHP - Select array based on value of which is within array

<?php
$salesArray = array(
    array(
        'key' => 'Basic Planners',
        'values' => array(
            array('x' => 'YourPhone', 'y' => 150),
            array('x' => 'Universe X3', 'y' => 300),
            array('x' => 'ePhone 74s', 'y' => 1500),
            array('x' => 'NextUs', 'y' => 50),
            array('x' => 'Humanoid', 'y' => 500)
        )
    ),
    array(
        'key' => 'No-Namers',
        'values' => array(
            array('x' => 'YourPhone', 'y' => 300),
            array('x' => 'Universe X3', 'y' => 250),
            array('x' => 'ePhone 74s', 'y' => 400),
            array('x' => 'NextUs', 'y' => 150),
            array('x' => 'Humanoid', 'y' => 900)
        )
    ),
    array(
        'key' => 'Feature Followers',
        'values' => array(
            array('x' => 'YourPhone', 'y' => 359),
            array('x' => 'Universe X3', 'y' => 900),
            array('x' => 'ePhone 74s', 'y' => 100),
            array('x' => 'NextUs', 'y' => 500),
            array('x' => 'Humanoid', 'y' => 250)
        )
    ),
    array(
        'key' => 'Hipsters & Elites',
        'values' => array(
            array('x' => 'YourPhone', 'y' => 200),
            array('x' => 'Universe X3', 'y' => 350),
            array('x' => 'ePhone 74s', 'y' => 50),
            array('x' => 'NextUs', 'y' => 800),
            array('x' => 'Humanoid', 'y' => 100)
        )
    )
  );




?>

<?php $needle = 'YourPhone'; ?>
<table>
    <?php foreach ($salesArray as $sale) { ?>
        <?php
        $key = null;
        foreach($sale['values'] as $index => $info) {
            if($info['x'] == $needle) {
            // if(stripos($info['x'], $needle) !== false) {
                $key = $index;
                break;
            }
        }
        ?>
        <tr>
           <td><?php echo $sale['key']; ?></td>
           <td><?php echo $sale['values'][$key]['y']; ?></td>
        </tr>
    <?php } ?>
</table>

//another way

<?php
$currentTeam = "YourPhone"; ?>

 <table>
   <?php foreach ($salesArray as $sale) { ?>

     <tr>
       <td><?php echo $sale['key']; ?></td>
       <td><?php
            foreach($sale['values'] as $values){
                if($values['x'] == $currentTeam )
                    echo $values['y'];
            }

        ?>
        </td>
     </tr>
   <?php } ?>
 </table>