Rash
Rash

Reputation: 896

how do I split array and show specific element

below is my array output

 [0] => Array
[OrderDetails] => Array
(

  [Options] => [Nicotine Level:12mg Nicotine][Sampler Item 1:Krankberry][Sampler Item 2:Unicorn Blood][Sampler Item 3:WaterFelons]
)
)

I want to show only Nicotine level from options field and, the options may vary,please help me.I have lot of options.

I have used below code

$explode_var = explode('[','[Nicotine Level:12mg Nicotine][Sampler Item 1:Krankberry][Sampler Item 2:Unicorn Blood][Sampler Item 3:WaterFelons]');

echo '<pre>';
print_r($explode_var);
echo '</pre>';

Upvotes: 0

Views: 49

Answers (1)

Prix
Prix

Reputation: 19528

This is one way to do it read the comments on the code:

<?php
$data = array(array('OrderDetails' => array('Options' => '[Nicotine Level:12mg Nicotine][Sampler Item 1:Krankberry][Sampler Item 2:Unicorn Blood][Sampler Item 3:WaterFelons]')));

$options = $data[0]['OrderDetails']['Options'];
$options = str_replace(']', '', $options);
$old_var = array_filter(explode('[',$options));
$result = array();
foreach ($old_var as $items)
{
    $item = explode(':', $items);
    $result[$item[0]] = $item[1];
}

foreach ($result as $key=>$value)
{
    echo $key, " => ", $value, "<br/>\n";
}

Live DEMO.

Upvotes: 2

Related Questions