0

I need some help setting up a PHP array. I get a little lost with multidimensional arrays.

Right now, I have an array with multiple products as follows:

If I do: print_r($products['1']); I get:

Array ( [0] => size:large [1] => color:blue [2] => material:cotton )

I can do print_r($products['2']); , etc and it will show a similar array as above.

I am trying to get it where I can do this:

echo $products['1']['color']; // the color of product 1

...and echo "blue";

I tried exploding the string and adding it to the array as follows:

$step_two = explode(":", $products['1']);

foreach( $step_two as $key => $value){

$products['1'][$key] = $value;

}

I know I'm obviously doing the explode / foreach way wrong but I wanted to post my code anyway. I hope this is enough information to help sort this out.

4
  • can we see how you build the array? Commented May 10, 2012 at 15:51
  • It's better to have the array created in the format that you want in the first place; rather than processing it after you have created the array. Commented May 10, 2012 at 15:57
  • Can you clarify if you're able to change how you initially set up that array (the clean way) or if you're trying to get from your present array structure to a more sensible one (the backwards-compatible way)? Commented May 10, 2012 at 16:03
  • Don't forget to accept the right answer if it was helpful. Commented May 10, 2012 at 16:26

6 Answers 6

3

Try this:

foreach ($products as &$product)
{
    foreach ($product as $key => $value)
    {
        list($attribute, $val) = explode(':',$value);
        $product[$attribute] = $val;

        // optional:
        unset($product[$key]);
    }
}
?>
Sign up to request clarification or add additional context in comments.

Comments

1

Here goes a sample that will convert from your first form to your desired form (output goes below)

<?php

$a = array( '1' => array('color:blue','size:large','price:cheap'));

print_r($a);

foreach ($a as $key => $inner_array) {
  foreach ($inner_array as $key2 => $attribute) {
    $parts = explode(":",$attribute);
    $a[$key][$parts[0]] = $parts[1];
    //Optional, to remove the old values
    unset($a[$key][$key2]);
  }
}

print_r($a);    
?>

root@xxx:/home/vinko/is# php a.php
Array
(
    [1] => Array
        (
            [0] => color:blue
            [1] => size:large
            [2] => price:cheap
        )

)
Array
(
    [1] => Array
        (
            [color] => blue
            [size] => large
            [price] => cheap
        )

)

Comments

0

You would be better of to build the array the right way, but to solve your problem you need to explode in the loop, something like:

foreach( $products['1'] as $value){
  $step_two = explode(":", $value);
  $products['1'][$step_two[0]] = $step_two[1];
}

You can wrap another foreach around it to loop over your whole $products array.

And you'd also better build a new array to avoid having both the old and the new values in your $products array.

Comments

0

You are right: you got the "foreach" and "explode" the wrong way around. Try something like this:

foreach($products['1'] as $param => $value) {
    $kv = explode(":", $value);
    if(count($kv) == 2) {
        $products[$kv[0]] = $kv[1];
        unset($products['1'][$param]);
    }
}

This code first loops over the sub-elements of your first element, then splits each one by the colon and, if there are two parts, sets the key-value back into the array.

Note the unset line - it removes array elements like $products['1'][1] after setting products['1']['color'] to blue.

Comments

0

If you already have $products structured in that way, you can modifty its structure like this:

$products = array(
  '1' => array(
    0 => 'size:large', 1 => 'color:blue', 2 => 'material:cotton'
  ),
  '2' => array(
    0 => 'size:small', 1 => 'color:red', 2 => 'material:silk'
  ),
);
foreach ($products as &$product) {
  $newArray = array();
  foreach ($product as $item) {
    list($key, $value) = explode(':', $item);
    $newArray[$key] = $value;
  }
  $product = $newArray;
}
print_r($products);

If you don't want to overwrite original $products array, just append $newArray to another array.

Comments

-2
<?php
  $products = array();
  $new_product = array();

  $new_product['color'] = "blue";
  $new_product['size'] = "large";
  $new_product['material'] = "cotton";

  $products[] = $new_product;

  echo $products[0]['color'];
  //print_r($products);

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.