简体   繁体   中英

How can I convert an array of strings into an associative array in PHP?

I currently have an array of three strings, and my goal is to turn these three strings from the array into individual associative arrays.

This is the array:

$arr = array(

  "action: Added; amount: 1; code: RNA1; name: Mens Organic T-shirt; colour: White; size: XL",

  "action: Subtracted; amount: 7; code: RNC1; name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y",

  "action: Added; amount: 20; code: RNV1; name: Gift Voucher; style: Mens; value: £20",

I'd like to have the key of the associative array be the action, quantity, item code etc and to start off I thought I should try turning the contents of the array into a string to make it more manageable.

// Convert $arr to a string.
$imploded = implode(": ",$arr);
//echo $imploaded;
$str = $imploded;
$results = preg_split('/: [;,]/', $str);
print_r($results);

Ideally, i'd like the array to look like this. I'm quite new to PHP so any help and advice would be much appreciated.

array(
    'action'    =>   '',
    'amount'    =>   '',
    'code'  =>   '',
    'name'  =>   '',
    'colour'    =>   '',
    'size'      =>   '',
);

This may be what you need:

<?php

$arr = array(   
  "action: Added; amount: 1; code: RNA1; name: Mens Organic T-shirt; colour: White; size: XL",    
  "action: Subtracted; amount: 7; code: RNC1; name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y",    
  "action: Added; amount: 20; code: RNV1; name: Gift Voucher; style: Mens; value: £20"
);
    


foreach ($arr as $string) {
   //Build array
   preg_match_all("/ [ ]?([^:]+): ([^;]+)[ ;]? /x", $string, $p);
   $array = array_combine($p[1], $p[2]);

   //Print it or do something else with it
    print_r($array);
}

https://3v4l.org/0cnhZ

You might want to check this as well:
PHP Split Delimited String into Key/Value Pairs (Associative Array)

You can use :

$tempArray = array();

foreach($arr as $data){
    $dataExplode = explode(';', $data);
      $temp = array();
    foreach($dataExplode as $key => $child){
              $childExplode = explode(':', $child);
              $temp[$childExplode[0]] = $childExplode[1];
    }
      array_push($tempArray, $temp);
}

print_r($tempArray); //to print array collection

You will get collection of seperate array()

As simple as:

$arr = array(
    "action: Added; amount: 1; code: RNA1; name: Mens Organic T-shirt; colour: White; size: XL",
    "action: Subtracted; amount: 7; code: RNC1; name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y",
    "action: Added; amount: 20; code: RNV1; name: Gift Voucher; style: Mens; value: £20",
);
  
$data = [];
foreach ($arr as $line) {
    $newItem = [];
    foreach (explode(';', $line) as $item) {
        $parts = explode(':', $item);
        $newItem[trim($parts[0])] = trim($parts[1]);
    }
    $data[] = $newItem;
}

print_r($data);

Fiddle here .

$arr = [
    "action: Added; amount: 1; code: RNA1; name: Mens Organic T-shirt; colour: White; size: XL",
    "action: Subtracted; amount: 7; code: RNC1; name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y",
    "action: Added; amount: 20; code: RNV1; name: Gift Voucher; style: Mens; value: £20",
];

$keyed = array_reduce($arr, function($collector, $value) {
    $collector[] = array_reduce(explode('; ', trim($value, '; ')), function($collector, $value) {
        $parts = explode(': ', $value);
        $collector[$parts[0]] = $parts[1];
        
        return $collector;
    }, []);
    
    return $collector;
}, []);

https://3v4l.org/lLl6T

One more solution without loops using:

$res = array_reduce(
    $arr, 
    function($acc, $item) {
        $s = array_reduce(
            explode(';', $item),
            function($a, $el) {
                $p = explode(': ', $el);
                $a[trim($p[0])] = trim($p[1]);
                return $a;
            },
            []
        );
        array_push($acc, $s);
        return $acc;
    },
    []
);
        
print_r($res);

Run PHP code here

Just for fun one more way to do it:

$arr = array(
  "action: Added; amount: 1; code: RNA1; name: Mens Organic T-shirt; colour: White; size: XL",
  "action: Subtracted; amount: 7; code: RNC1; name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y",
  "action: Added; amount: 20; code: RNV1; name: Gift Voucher; style: Mens; value: £20",
);

$result = array_map(function($line) {
    return array_combine(...array_map(null, ...array_chunk(preg_split('/[:;]\s+/', $line), 2)));

}, $arr);

print_r($result);

Basically here we split the line by the two possible separators either : or ; followed by spaces.

Then the array_chunk function groups the key and values together and we get for each line something like this:

        Array
        (
            [0] => Array
                (
                    [0] => action
                    [1] => Added
                )

            [1] => Array
                (
                    [0] => amount
                    [1] => 1
                )
* * *

By spreading and mapping the array above we get it's rotated version like this:

Array
        (
            [0] => Array
                (
                    [0] => action
                    [1] => amount
* * *
                )

            [1] => Array
                (
                    [0] => Added
                    [1] => 1
* * *
                )
        )

We can now spread this array and pass it to the array_combine function so we have a nice associative array filled with the desired keys and values.

Then we map all lines and this way we get the nicely formatted result.

Here is the final fiddle.

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