2

I have a flat array of pipe-delimited strings:

Array
(
    [0] => style1|000000
    [1] => style2|ff6600
)

I iterate the data like this:

foreach ($styles as $key => $value) {
    $sort_values[] = explode('|', $value);
}

print_r($sort_values) shows:

Array
(
    [0] => Array
        (
            [0] => style1
            [1] => 000000
        )
    [1] => Array
        (
            [0] => style2
            [1] => ff6600
        )
)

I would actually like a transposed structure with associative first level keys:

Array
(
    [styles] => Array
        (
            [0] => style1
            [1] => style2
        )
    [links] => Array
        (
            [0] => 000000
            [1] => ff6600
        )
)
3
  • what does the $styles array look like? Commented Oct 24, 2012 at 2:10
  • @PhillPafford just updated the question Commented Oct 24, 2012 at 2:13
  • How does the data get into your styles array? Does it come from text? Commented Oct 24, 2012 at 2:28

2 Answers 2

5

Assuming your input array looks like

array('style1|000000','style2|ff6600', 'style3|22ff22')

You need a little more logic in your loop.

// Initialize output array with an empty styles subarray and a links subarray
$out = array('styles'=>array(), 'links'=>array());
foreach ($styles as $key=>$value) {
   // Loop over and split on the |
   list($style, $link) = explode("|", $value);
   // And append the two resultant values to their respective subarrays via []
   $out['styles'][] = $style;
   $out['links'][] = $link;

   // list() is a useful construct for producing readable results with small arrays,
   // but I could also have used an array to receive the 
   // results of explode()
   // $split = explode("|", $value);
   // $out['styles'][] = $split[0];
   // $out['links'][] = $split[1];

}
print_r($out);

// Prints:
Array
(
    [styles] => Array
        (
            [0] => style1
            [1] => style2
            [2] => style3
        )

    [links] => Array
        (
            [0] => 000000
            [1] => ff6600
            [2] => 22ff22
        )

)
Sign up to request clarification or add additional context in comments.

1 Comment

@Benn Every question deserves an answer with a solid explanation. Code solutions without explanations are just solutions, not answers.
0

You can use explode() or sscanf() to parse those pipe-delimited strings.

Code: (Demo) (w/ explode())

$result = [];
foreach ($array as $v) {
    sscanf($v, '%[^|]|%s', $result['style'][], $result['links'][]);
    // [$result['style'][], $result['links'][]] = explode('|', $v);
}
var_export($result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.