How to clean a PHP multidimensional associative array to map with javascript es6
Get the solution ↓↓↓I have a PHP multidimensional associative array like this:
$matchs = array(
'10689' => array(
'id' => '10689',
'sport' => 'Football',
'player_1' => array(
'id' => '22',
'name' => 'Mike Oldfield',
'odds' => array(
'bookie_1' => '1.20',
'bookie_2' => '1.21',
'bookie_3' => '1.22'
)
),
'player_2' => array(
'id' => '122',
'name' => 'Fran Sinatra',
'odds' => array(
'bookie_1' => '4.10',
'bookie_2' => '4.11',
'bookie_3' => '4.22'
)
)
),
'10829' => array(
'id' => '10829',
'sport' => 'Basketball',
'player_1' => array(
'id' => '522',
'name' => 'Frank Black',
'odds' => array(
'bookie_1' => '2.01',
'bookie_2' => '2.02',
'bookie_3' => '2.04'
)
),
'player_2' => array(
'id' => '122',
'name' => 'Freddie Mercury',
'odds' => array(
'bookie_1' => '1.87',
'bookie_2' => '1.86',
'bookie_3' => '1.85'
)
)
),
);
I need to pass that array to React App. Then I make something like this:
<?php echo json_encode($matchs, JSON_FORCE_OBJECT); ?>
Then withaxios
(I have also tried with jquery and other libraries) I get the json file. Everything perfect for now.
The problem comes when I try to traverse the array. I get an error 'TypeError: xxx.map is not a function'. Thanks to this thread what has been achieved in part: React: Map multidimensional array with different keys
The question is how could I remove the keys of this array to traverse without usingObject.keys
I have triedecho json_encode(array_values($matchs, JSON_FORCE_OBJECT))
, the problem is that it only eliminates the keys of the first level. In my array example 'player_1', 'player_2' and 'odds' remains.
Answer
Solution:
Looking at your associative array structure, I realise that the JSON form of$matches
will look something like,
{"10689":{"id":"10689","sport":"Football", ...
and when you decode this JSON in javascript, it becomes anobject
andobject.map
is not a valid method call (as.map
is only applicable for arrays and not objects).
you will probably have to useObject.keys(<your_json>).map
.
If you don't need keys, you can useObject.values(<your_json>).map
Hope it helps.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: filter_sanitize_string
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.