How to show JSON data with Associate Array Key? - php

in the below code, i used simple $key,$value but i want to use that code with associate array key. Then how can i do? Please help.
<?php
function custom_table_page_display() {
$jsonData = '{ "User":"John", "Age":22, "Country":"India" }';
$phpArray = json_decode($jsonData);
$rows = array();
foreach($phpArray as $key => $value)
{
$rows[] = $key;
$value1[]=$value;
}
$header=$rows;
$value11[]=$value1;
$output = theme('table',array('header'=>$header,'rows' => $value11));
return $output;
}
?>

You need to use
$phpArray = json_decode($jsonData, true);
The second argument says whether to return an associative array or object for a JSON object. By default it returns an object.
You can replace your foreach loop with:
$rows = array_keys($phpArray);
$value1 = array_values($phpArray);
For the data you gave in the comment below, you would do:
$rows = array_keys($phpArray['Class'][0]);
$values = array_map('array_values', $phpArray['Class']);
$values will then be a 2-dimensional array of values:
[ [ "John", 22, "India" ],
[ "Sam", 23, "Argentina" ],
[ "John", 22, "Algeria" ]
]
DEMO

Related

Convert multiple values ​from a string to php json

I am trying to get results when converting a url to json. I thank those who can help me, thank you.
I have this string: id_user123=123;456;789&id_user456=333;545;908
I would like to get this result:
{"result": [
{"id_user123":[ "123", "456", "789" ] },
{"id_user456":[ "333", "545", "908" ] }
]}
Use parse_​url to get the "query" part of your string
and parse_str to get each parameter and values.
<?php
$url = 'test.php?id_user123=123;456;789&id_user456=333;545;908';
parse_str(parse_url($url, PHP_URL_QUERY), $queryArray);
$result = [];
foreach ($queryArray as $userId => $values) {
$result['result'][] = [
$userId => explode(';', $values)
];
}
echo "<pre>";
echo json_encode($result, JSON_PRETTY_PRINT);
echo "</pre>";
will output
{
"result": [
{
"id_user123": [
"123",
"456",
"789"
]
},
{
"id_user456": [
"333",
"545",
"908"
]
}
]
}
Simple loop with explode():
$result = ['result' => []];
foreach ($_GET as $userId => $values) {
$result[] = [
$userId => explode(';', $values);
];
}
echo json_encode($result);

Convert flat array of string into associative array

I want to convert this array of string;
$arList = ["the","quick","brown","fox"];
into this format.
[
"the" => [
"quick" => [
"brown" => []
]
]
]
Sorry for not posting some code.
here is what I tried,
<?php
$arList = ["the","quick","brown","fox"];
$newList = [];
$pointer = $newList;
foreach($arList as $item) {
$pointer[$item] = [];
$pointer = &$newList[$item];
}
echo "<pre>";
print_r($newList);
echo "</pre>";
I found a solution from the net using the following code;
$result = array_reduce(array_reverse($arList), function($prevArray, $key){
return $prevArray ? [$key => $prevArray] : [$key];
}, null);

How to convert a PHP array into json string

I have a PHP array built with a while loop. I do successfully convert it to JSON string, however the output is not what I want and need some help to get it right:
My current code:
while(!$sql_query->EOF){
$data[] = array(
'id' => $id,
'name' => $name,
'title' => $title
);
$sql_query-> MoveNext(); }
echo json_encode($data);
The output I get with my code is this:
[
{
"id":"1",
"name":"Nick",
"title":"Office"
},
{
"id":"2",
"name":"Amy",
"title":"Home"
}
]
However, I need the outcome to be:
{
"data": [
[
"1",
"Nick",
"Office"
],
[
"2",
"Amy",
"Home"
]
]
}
I tired paying around with array_values() but no success so far.
Can somebody suggest the right approach here?
When building your array, don't add the keys to the values, this will allow the encoding to use array notation, then add the "data" key as part of the encode...
$data = [];
while(!$sql_query->EOF){
$data[] = [ $id, $name,$title];
$sql_query-> MoveNext();
}
echo json_encode(["data" => $data]);
If you do something like:
$result = (object)["data" => $data];
echo json_encode($data);
this will give you the output you require.
First of all you have to modify you array
$newData = [];
foreach($data as $item) {
$newData[] = array_values($item);
}
and then create new array
echo json_encode(["data"=>$newData])

How to extract perticular array value from multidimentional array

How can I get the list of all ids from the array given below,
$filteredZips=[{
"id": 21,
"distance": "0"
},
{
"id": 20,
"distance": "3.9399923305414037"
},
{
"id": 29,
"distance": "8.33045537474091"
}]
Expected result will be :
$id = array('21','20','29');
There is a function called array_column that will grab one column in an array.
First the string needs to be converted to array with Json_decode and second parameter to true.
Then array_column returns your expected output.
No looping is needed.
$filteredZips='[{
"id": 21,
"distance": "0"},{
"id": 20,
"distance": "3.9399923305414037"},{
"id": 29,
"distance": "8.33045537474091"}]';
$filteredZipsarr = json_decode($filteredZips,true);
$id = array_column($filteredZipsarr, "id");
Var_dump($id);
https://3v4l.org/hFOKR
If you don't need the $filteredZipsarr you can make it a one liner:
$id = array_column(json_decode($filteredZips,true), "id");
Use array_map function:
$id = array_map(function($value){
return $value['id'];
}, $filteredZips);
Documentation: http://php.net/manual/en/function.array-map.php
First you need to decode JSON string to access it as Array of Objects :
$filteredZips = json_decode($filteredZips);
$results = array();
foreach ($filteredZips as $zip) {
$results[] = $zip->id;
}
print_r($results);
Check here : https://3v4l.org/kfkhV
Use array_column after transform your JSON with json_decode
$ids = array_column(json_decode($filteredZips, true), 'id');
Array
(
[0] => 21
[1] => 20
[2] => 29
)
Solution:
$answer = [];
foreach($filteredZips as $array){
if(isset($array['id'])){
$answer[]=$array['id'];
}
}
var_dump($answer);
Try this:
$ids = array();
foreach ($filteredZips as $zip) {
$ids[] = $zip["id"];
}
var_dump($ids);
Dont forget to use json_decode function to get a proper php array.

First key of php associative array returns undefined index when parsed from CSV

I am having trouble accessing the first index of an associative array when parsing from a csv.
CSV:
ID,COLOR
1,Red
2,Green
3,Blue
PHP:
function associative_array_from_csv($csv)
{
$rows = array_map('str_getcsv', file($csv));
$header = array_shift($rows);
$array = array();
foreach($rows as $data) {
$array[] = array_combine($header, $data);
}
return $array;
}
$colors = associative_array_from_csv($csv);
Now $colors returns:
[
[
"ID" => "1",
"COLOR" => "Red",
],
[
"ID" => "2",
"COLOR" => "Green ",
],
[
"ID" => "3",
"COLOR" => "Blue",
],
];
But if I try to access the ID of any color:
$colors[0]["ID"] // returns undefined index: ID
$colors[0]["COLOR"] // returns "Red"
If I loop over the colors I can access the ID like so:
foreach($colors as $color)
{
print_r(reset($color)); // Prints the ID
}
But why I can't access it directly like $colors[0]["ID"]?
Thanks
I had the same issue. The problem was that Excel adds a hidden character to the first cell in the document, for encoding UTF-8 BOM.
I could see this when running:
var_dump(json_encode($array));
This would return:
string(312) "[{"\ufeffemail":"test#me.com","firstName":"import","lastName":"test"},{"\ufeffemail":"test#comcast.net","firstName":"import","lastName":"test"}]"
To remove the \ufeff character, I did:
$header = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $header);
In this case, that would be:
function associative_array_from_csv($csv)
{
$rows = array_map('str_getcsv', file($csv));
$header = array_shift($rows);
$header = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $header);
$array = array();
foreach($rows as $data) {
$array[] = array_combine($header, $data);
}
return $array;
}
This worked for me!
header = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $header);

Categories