简体   繁体   中英

How to convert key value pair string into a array in php

I will get the following values from checkbox.

attribute_value:samsung,attribute_id:1,spec_group_id:2,prod_id:1

I need to convert the above string as array format and get the variable outside the loop as sinlge array.

so that if I need to get Array[attribute_value] .

for ($i=0; $i < count($data_search) ; $i++) 
    { 
        $row = $data_search[$i];

        echo $row['search_id'];
        echo "</br>";

        $xx = "prod_id:".$row['search_id'];
        echo $xx;
        echo "</br>";
        // echo $checkbox_value = $_POST['collection'] ;

        foreach($_POST['collection'] as $value)
        {
            // echo $value;
          $ff = $value.','.$xx;
          echo $ff;
          echo "</br>";
            // here I will get the output string.
          attribute_value:samsung,attribute_id:1,spec_group_id:2,prod_id:1

        }
}

I think you want the logic as follows, If you need something different please let me know..

$string = "attribute_value:samsung,attribute_id:1,spec_group_id:2,prod_id:1";
$a1 = explode(",",$string);
$array = [];
foreach($a1 as $a){
  $innerArray = explode(':',$a);
  $array[$innerArray[0]] = $innerArray[1];
}

print_r($array);

Perhaps the following might be of help - though I had no way to test

# store the final output in this array - outside the loop(s)
$arr=array();

# process the `$data_search` array using `foreach` rather than `for` loop
foreach( $data_search as $i => $row ){

    #construct the portion to be appended to string
    $xx = sprintf( 'prod_id:%s', $row['search_id'] );
    
    # process the POST data
    foreach( $_POST['collection'] as $value ){
        # The value of $value here is, for example: attribute_value:samsung,attribute_id:1,spec_group_id:2
        $ff=sprintf( '%s,%s', $value, $xx );
        # when the previous string is appended you get: attribute_value:samsung,attribute_id:1,spec_group_id:2,prod_id:1 etc
        
        # a temporary array that will hold the individual pieces from this string when exploded
        $tmp=array();
        
        # explode the string by comma
        $pairs=explode( ',', $ff );
        
        # process this array and explode the name/value pairs by colon
        foreach( $pairs as $i => $value ){
            # get reference to name/value
            list($a,$v)=explode(':',$value);
            
            #add to tmp array
            $tmp[]=array(
                'attribute' =>  $a,
                'value'     =>  $v
            );
        }
        #add to final output.
        $arr[]=$tmp;
    }
}

# $arr should now be a multi-dimensional array

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