简体   繁体   中英

create associative array from array

How can I transform

Array1
(
    [0] => Some Text
    [1] => Some Other Text (+£14.20)
    [2] => Text Text (+£26.88)
    [3] => Another One (+£68.04)
)

Into associative array like the one below:

Array2
(
    [Some Text] => 0 //0 since there is no (+£val) part
    [Some Other Text] => 14.20
    [Text Text] => Text Text 26.88
    [Another One] => 68.04
)
$newArray = array();
foreach( $oldArray as $str ) {
    if( preg_match( '/^(.+)\s\(\+£([\d\.]+)\)$/', $str, $matches ) ) {
        $newArray[ $matches[1] ] = (double)$matches[2];
    } else {
        $newArray[ $str ] = 0;
    }
}

Something like this should work:

$a2 = array();
foreach ($Array1 as $a1) {
    if (strpos($a1, '(') > 0) {
      $text = substr($a1, 0, strpos($a1, '('));
      $value = substr($a1, strpos($a1, '(')+3, strpos($a1, ')')-1);
    } else {
      $text = $a1;
      $value = 0;
    }
    $a2[$text] = $value;    
}
print_r($a2);

EDIT:

You can do this using explode method as well:

$a2 = array();
foreach ($Array1 as $a1) {
    $a1explode = explode("(", $a1, 2);
    $text = $a1explode[0];
    if ($a1explode[1]) {
       $value = substr($a1explode[1],3);
    } else {
       $value = 0;
    }
    $a2[$text] = $value;    
}
print_r($a2);

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