php - Convert Array with foreach loop
Get the solution ↓↓↓Solution:
You can try something like this (now i have tested it!):
foreach($myarray[0] as $titleKey=>$title) {
echo $title . " = ";
for($i = 1;$i<count($myarray);$i++) {
echo $myarray[$i][$titleKey] . ",";
}
echo "</br>";
}
Answer
Solution:
Use array_combine for this
$myarray = [
['Type', 'Brand'],
['Car', 'Toyota']
];
list($fields, $values) = $myarray;
$output = array_combine($fields, $values);
echo json_encode($output, JSON_PRETTY_PRINT);
// {
// "Type": "Car",
// "Brand": "Toyota"
// }
But as you said, it could have more values than just the Toyota, so you'd have to do it like this
$myarray = [
['Type', 'Brand'],
['Car', 'Toyota'],
['Horse', 'Seabiscuit']
];
function first ($xs) { return $xs[0]; }
function rest ($xs) { return array_slice($xs, 1); }
$output = array_map(function ($values) use ($myarray) {
return array_combine(first($myarray), $values);
}, rest($myarray));
echo json_encode($output, JSON_PRETTY_PRINT);
// [
// {
// "Type": "Car",
// "Brand": "Toyota"
// },
// {
// "Type": "Horse",
// "Brand": "Seabiscuit"
// }
// ]
Note, this final solution assumes that the first array would contain the field names and the remaining arrays would have the values
Of course this works when more fields are added, too. No changes to the code are necessary.
$myarray = [
['Type', 'Brand', 'Origin'],
['Car', 'Toyota', 'Japan'],
['Horse', 'Seabiscuit', 'Kentucky']
];
function first ($xs) { return $xs[0]; }
function rest ($xs) { return array_slice($xs, 1); }
$output = array_map(function ($values) use ($myarray) {
return array_combine(first($myarray), $values);
}, rest($myarray));
echo json_encode($output, JSON_PRETTY_PRINT);
// [
// {
// "Type": "Car",
// "Brand": "Toyota",
// "Origin": "Japan"
// },
// {
// "Type": "Horse",
// "Brand": "Seabiscuit",
// "Origin": "Kentucky"
// }
// ]
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: illegal string offset
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.