MultiDev
MultiDev

Reputation: 10649

How to setup a PHP multidimensional array and declare the array keys?

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.

Upvotes: 0

Views: 1559

Answers (6)

galymzhan
galymzhan

Reputation: 5523

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.

Upvotes: 0

Vinko Vrsalovic
Vinko Vrsalovic

Reputation: 340286

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
        )

)

Upvotes: 1

jessica
jessica

Reputation: 3141

Try this:

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

        // optional:
        unset($product[$key]);
    }
}
?>

Upvotes: 3

Aleks G
Aleks G

Reputation: 57326

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.

Upvotes: 0

jeroen
jeroen

Reputation: 91742

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.

Upvotes: 0

Nathaniel Ford
Nathaniel Ford

Reputation: 21239

<?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);

Upvotes: -2

Related Questions