I have a function for arrays that I insert in db.
$data = array(
"This\tIs\tAn\tExample\tOne\tOf\tMy\tArrays\"
);
I formatted it correctly and given output is with:
$result = array_walk($data, function(&$item) { $item = '{ ' .str_replace("\t", ', ', $item) . ' }'; });
and the result of one of the rows that is inserted in db in JSON format is:
{ This, is, Example }, { One, Of, My, Arrays}
and all of them are formatted that way.
How can I bypass this to get desired format like:
{ This, is, Example, One, Of, My, Arrays}
If you want to convert this
$data = array(
"This\tIs\tAn\tExample\tOne\tOf\tMy\tArrays\"
);
to this
{ This, is, Example, One, Of, My, Arrays}
you can simply do it by
$result = [];
foreach ($data as $index => $value) {
$result[] = implode(',', explode("\t", $value));
}
$result = '{' . implode(',', $result) . '}';
Related
So I would like to create just one loop to parse the json data i have. I can successfully parse it in 2 foreach loops however when trying to combine in one loop using $key => $value the $key returns nothing when called. How can I successfully take the 2 foreach loops I have here and combine them into one?
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key) {
$GenreID = $key['id'].'<br>';
echo $GenreID;
}
foreach($jsonList as $key => $value) {
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
The json data is as follows:
{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":10751,"name":"Family"},{"id":14,"name":"Fantasy"},{"id":36,"name":"History"},{"id":27,"name":"Horror"},{"id":10402,"name":"Music"},{"id":9648,"name":"Mystery"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10770,"name":"TV Movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}
You can still use $key as an index when also extracting the $value.
However note that you shouldn't be assigning the line breaks to your variables, and should instead consider them part of the view by echoing them out independently:
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key => $value) {
$GenreID = $key['id']; // Depending on structure, you may need $value['id'];
$GenreName = $value['name'];
echo $GenreID . '<br>';
echo $GenreName . '<br><br>';
}
Your single loop below here.
foreach($jsonList as $key)
{
$GenreID = $key['id'].'<br>';
echo $GenreID;
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
$key is a assosative array.Therefore it had some index.So you can use this index in single loop.
It seems you get confused over your data structure. Seeing the json, the resulting "$jsonlist" supposed to contain array with id and value as keys.
You can iterate over it and extract the the appropriate key.
Myabe something like this:
foreach($jsonlist as $value) {
echo "id: " . $value['id'] . "\n";
echo "name: " . $value['name'] . "\n";
}
extra bonus, if you want to create 1 level array from your json based on id with the name you could try array reduce using anon function like this:
$jsonlist = array_reduce($jsonlist, function($result, $item){
$result[$item['id']] = $item['name'];
return $result;
}, []);
extra neat for transformation of static structure data.
I am trying to loop through a JSON Array returning a unique date and all the tasks associated with that date.
This is an example of my JSON array:
<!-- language: lang-json -->
[
{
"task":"Clean my teeth",
"date":"today"
},
{
"task":"Jumping Jacks",
"date":"tomorrow"
},
{
"task":"Call Mom",
"date":"today"
},
{
"task":"Wash The Dog",
"date":"2017/03/01"
},
{
"task":"Clean The House",
"date":"today"
}
]
I want to display something like this:
Today
Clean my teeth
Call Mom
Tomorrow
Jumping Jacks
2017/03/01
Clean The House
Here is my function: I can get all the unique days but I'm not sure how to display the tasks associated with that day.
public static function Iteration()
{
$file = file_get_contents("newfile.php");
$result = rtrim( $file, ",");
$array = json_decode('[' . $result . ']');
$unique_dates = array();
$unique_tasks = array();
foreach($array as $item) {
if ( in_array($item->date, $unique_dates) ) {
continue;
}
$unique_dates[] = $item->date;
$time = strtotime($item->date);
$newformat = date('Y-m-d',$time);
echo '<h2>' . $newformat . '</h2>';
echo $item->task;
}
}
You can traverse the JSON list, and keep the unique records and store tasks at the same traversal.
By using the isset(), you can determine whether the key is unique or not.
Try this:
<?php
$json = '[{"task": "Clean my teeth","date": "today"},{"task": "Jumping Jacks","date": "tomorrow"},{"task": "Call Mom","date": "today"},{"task": "Wash The Dog","date": "2017/03/01"},{"task": "Clean The House","date": "today"}]';
$array = json_decode($json);
$res = array();
foreach ($array as $each) {
if (isset($res[$each->date]))
array_push($res[$each->date], $each->task);
else
$res[$each->date] = array($each->task);
}
foreach ($res as $date => $tasks){
echo "<h3>{$date}</h3>";
foreach ($tasks as $task)
echo "<p>$task</p>";
}
I'm trying to convert my array to JSON.
My JSON is stored in the database and will later be decoded for permission checking.
Example,
How I want it to be stored in the database:
{ "admin": 1,
"create_posts": 1,
"edit_posts": 1,
"delete_posts": 1 }
How it is being stored now:
{"0":"\"admin\": 1",
"1":"\"create_posts\": 1",
"2":"\"edit_posts\": 1",
"3":"\"delete_posts\": 1"}
My code:
$check_list = $_POST['check_list'];
$list = array();
foreach($check_list as $key) {
$key = '"' . $key .= '": 1';
array_push($list, $key);
}
$json = json_encode($list, JSON_FORCE_OBJECT);
How would I make it so that it stores in the database like I want it to be?
I'm quite new to this, so any hints instead of direct answers is also much appreciated!
UPDATE:
JSON decode and validation:
$permis = json_decode($permissions->permissions, true);
echo ($permis['admin'] == true) ? 'allowed' : 'disallowed';
$arr = [ 'a', 'b', 'c' ];
echo json_encode(
array_combine(
$arr,
array_fill(0, count($arr), 1)
),
JSON_PRETTY_PRINT
);
Output:
{
"a": 1,
"b": 1,
"c": 1
}
http://us3.php.net/manual/en/function.array-combine.php
http://us3.php.net/manual/en/function.array-fill.php
I'm assuming the incoming data looks like this.
$incoming_data = "admin=1&create_posts=1&edit_posts=1&delete_posts=1";
$pairs = parse_str($incoming_data);
so we take the incoming pairs and use the $key as the array index so you don't get the extra array element index.
$permissions = array();
foreach($pairs as $key => $value){
$permissions[$key] = $value;
}
then we encode the new array to get the JSON you're looking for.
print json_encode($permissions);
will print out JSON like this:
{
"admin":"1",
"create_posts":"1",
"edit_posts":"1",
"delete_posts":"1"
}
The main thing to change in your code is this.
foreach($check_list as $key) {
$list[$key] = 1;
}
I got stuck somehow on the following problem:
What I want to achieve is to merge the following arrays based on key :
{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}
Which needs to output like this:
[{"item_header":"Entities"},
{"list_items" :
[{"submenu_id":"Parents","submenu_label":"parents"},
{"submenu_id":"Insurers","submenu_label":"insurers"}]
}]
[{"item_header":"Users"},
{"list_items" :
[{"submenu_id":"New roles","submenu_label":"newrole"}
{"submenu_id":"User - roles","submenu_label":"user_roles"}
{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}]
}]
[{"item_header":"Accounting"},
{"list_items" :
[{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}]
}]
I have been trying all kinds of things for the last two hours, but each attempt returned a different format as the one required and thus failed miserably. Somehow, I couldn't figure it out.
Do you have a construction in mind to get this job done?
I would be very interested to hear your approach on the matter.
Thanks.
$input = array(
'{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}',
'{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}',
'{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}',
'{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}',
'{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}',
'{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}',
);
$input = array_map(function ($e) { return json_decode($e, true); }, $input);
$result = array();
$indexMap = array();
foreach ($input as $index => $values) {
foreach ($values as $k => $value) {
$index = isset($indexMap[$k]) ? $indexMap[$k] : $index;
if (!isset($result[$index]['item_header'])) {
$result[$index]['item_header'] = $k;
$indexMap[$k] = $index;
}
$result[$index]['list_items'][] = $value;
}
}
echo json_encode($result);
Here you are!
In this case, first I added all arrays into one array for processing.
I thought they are in same array first, but now I realize they aren't.
Just make an empty $array=[] then and then add them all in $array[]=$a1, $array[]=$a2, etc...
$array = '[{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}},
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}},
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}},
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}},
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}},
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}]';
$array = json_decode($array, true);
$intermediate = []; // 1st step
foreach($array as $a)
{
$keys = array_keys($a);
$key = $keys[0]; // say, "Entities" or "Users"
$intermediate[$key] []= $a[$key];
}
$result = []; // 2nd step
foreach($intermediate as $key=>$a)
{
$entry = ["item_header" => $key, "list_items" => [] ];
foreach($a as $item) $entry["list_items"] []= $item;
$result []= $entry;
}
print_r($result);
I would prefer an OO approach for that.
First an object for the list_item:
{"submenu_id":"Parents","submenu_label":"parents"}
Second an object for the item_header:
{"item_header":"Entities", "list_items" : <array of list_item> }
Last an object or an array for all:
{ "Menus: <array of item_header> }
And the according getter/setter etc.
The following code will give you the requisite array over which you can iterate to get the desired output.
$final_array = array();
foreach($array as $value) { //assuming that the original arrays are stored inside another array. You can replace the iterator over the array to an iterator over input from file
$key = /*Extract the key from the string ($value)*/
$existing_array_for_key = $final_array[$key];
if(!array_key_exists ($key , $final_array)) {
$existing_array_for_key = array();
}
$existing_array_for_key[count($existing_array_for_key)+1] = /*Extract value from the String ($value)*/
$final_array[$key] = $existing_array_for_key;
}
the given code below insert data from an array to the mysql table.as its not the full code but what i want to know is available in this code. my question is that there is a field in table named "image_url" but the data in that field only have image name and i want to append http://www.xxxxxx.com at the start of every image name and the replace it with the image name in the field but i dont know how to do that plz help me out
thanks in advance
function putTest($t) {
//$c = connect();
foreach ($t as $k => $v) {
$query = "INSERT INTO test (".implode(',',array_keys($v)).") VALUES ('".implode("','",$v)."')";
//echo "<pre>";
// echo $query;
$r = mysql_query($query);
}
//mysql_close($c);
}
This snippet should do what you want:
if (isset($v['image_url'])) {
$v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
}
You can concatenate strings with the dot "."!
At first... Is your application protected against SQL injection? If not you should build two methods/functions like this using mysql_real_escape_string():
function sqlSafeKey( $key){
return '`' . mysql_real_escape_string( $key) . `'`;
}
function sqlSafeValue( $value){
return "'" . mysql_real_escape_string( $value) . "'";
}
And than use array_map() to escape your values like this:
$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);
About your question... The matzino's answer is correct and whole loop should look like this:
function putTest($t) {
//$c = connect();
foreach ($t as $k => $v) {
$v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);
$query = "INSERT INTO test (".implode(',', $keys).
") VALUES ('".implode("','",$values)."')";
//echo "<pre>";
// echo $query;
$r = mysql_query($query);
}
//mysql_close($c);
}