php - Separating array rows into other arrays based on key name -
i have array this
$rows = array( array( 'fruit.name' => 'apple', 'fruit.colour' => 'red', 'fruit.weight' => '0.1', 'vegetable.name' => 'carrot', 'vegetable.colour' => 'orange', 'vegetable.weight' => '0.05' ), array( 'fruit.name' => 'banana', 'fruit.colour' => 'yellow', 'fruit.weight' => '0.7', 'vegetable.name' => 'potato', 'vegetable.colour' => 'brown', 'vegetable.weight' => '0.6' ) );
and want able sort array 2 other arrays called 'fruits' , 'vegetables' based on first part of key name decimal point. array should have 2 rows in each of fruits , vegetable arrays.
i have code doesn't work , can't see i'm doing wrong.
$fruits = array(); $vegetables = array(); foreach($rows $row) { foreach($row $key => $value) { if('fruit' == substr($key, 0, strpos($key, '.'))) { $fruits[$key] = $row; } else { $vegetables[$key] = $row; } } } echo "<pre>"; var_dump($fruits); echo "</pre>";
when var_dump this
array(3) { ["fruit.name"]=> array(6) { ["fruit.name"]=> string(6) "banana" ["fruit.colour"]=> string(6) "yellow" ["fruit.weight"]=> string(3) "0.7" ["vegetable.name"]=> string(6) "potato" ["vegetable.colour"]=> string(5) "brown" ["vegetable.weight"]=> string(3) "0.6" } ["fruit.colour"]=> array(6) { ["fruit.name"]=> string(6) "banana" ["fruit.colour"]=> string(6) "yellow" ["fruit.weight"]=> string(3) "0.7" ["vegetable.name"]=> string(6) "potato" ["vegetable.colour"]=> string(5) "brown" ["vegetable.weight"]=> string(3) "0.6" } ["fruit.weight"]=> array(6) { ["fruit.name"]=> string(6) "banana" ["fruit.colour"]=> string(6) "yellow" ["fruit.weight"]=> string(3) "0.7" ["vegetable.name"]=> string(6) "potato" ["vegetable.colour"]=> string(5) "brown" ["vegetable.weight"]=> string(3) "0.6" } }
any please getting separate array 2 arrays each containing either fruits or vegetables.
this seems work:
$rows = array( array( 'fruit.name' => 'apple', 'fruit.colour' => 'red', 'fruit.weight' => '0.1', 'vegetable.name' => 'carrot', 'vegetable.colour' => 'orange', 'vegetable.weight' => '0.05' ), array( 'fruit.name' => 'banana', 'fruit.colour' => 'yellow', 'fruit.weight' => '0.7', 'vegetable.name' => 'potato', 'vegetable.colour' => 'brown', 'vegetable.weight' => '0.6' ) ); $fruits = $vegs = array(); foreach ($rows $arrays) { $fruit = array(); $veg = array(); foreach ($arrays $key => $val) { $index = substr($key, strpos($key, ".") + 1); if('fruit' == substr($key, 0, strpos($key, '.'))){ $fruit[$index] = $val; } else { $veg[$index] = $val; } } $fruits[] = $fruit; $vegs[] = $veg; } var_dump($fruits, $vegs);
(please overlook fact i've called 1 of vars $vegs
)
hope helps!
Comments
Post a Comment