Skip to content
Advertisement

How can I get each value of array in PHP?

I get an endpoint which take some products of the database.

That’s endpoint brings a JSON which looks like this:

idProduct   
  0 => "21"
colour  
  0 => "Red"
  1 => "Green"
size    
  0 => "M"
  1 => "XS"

So, I need to make a table which shows colour[0] with size[0], colour[1] with size[1], etc.

The main problem is that I can’t access by the name of the column (size and colour), because in another case, the name can be ability, might, darkness, etc.

I tried this but doesn’t works.

echo '<tbody>';
foreach ($array_from_json as $key => $value) {
  for ($i=0; $i <= count($value) ; $i++) { 
    echo "<tr><td>".$value[$i]."</td></tr>";
  }
}
echo '</tbody>';

The array ($array_from_json) shows this in a var_dump:

array(3) { ["idProducto"]=> array(1) { [0]=> string(1) "9" } ["color"]=> array(2) { [0]=> string(4) "Azul" [1]=> string(5) "Verde" } ["talla"]=> array(2) { [0]=> string(1) "L" [1]=> string(2) "XL" } }

The JSON raw is: {"idProducto":["9"],"color":["Azul","Verde"],"talla":["L","XL"]}

Advertisement

Answer

You can do something like this:

You can get the column names using array_keys function, you have to delete the first column name “idProducto” (because you don’t want to iterate over it). This code will work regardless of the column names you choose.

Input data (json):

$json = '{"idProducto":["9"],"color":["Azul","Verde"],"talla":["L","XL"]}';

Php code:

$product = json_decode($json, true); //Convert a Json string to array

$keys = array_keys($product); //Get arrays keys

array_shift($keys); //Delete first key "idProducto"

echo '<table>';

for($i = 0; $i < count($product[$keys[0]]); $i++) {
    
    echo '<tr>';
    
    foreach($keys as $key) {        
        echo '<td>' . $product[$key][$i] . '</td>';
    }
    
    echo '</tr>';
}
echo '</table>';

Output (without table head, but you can add with a foreach at the beginning):

color talla
Azul L
Verde XL
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement