Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 20,946
» Latest member: blackopsdlc
» Forum threads: 21,996
» Forum posts: 22,963

Full Statistics

Online Users
There are currently 1196 online users.
» 0 Member(s) | 1191 Guest(s)
Applebot, Baidu, Bing, Facebook, Google

Latest Threads
[PS.Blog] Fading Echo mak...
Forum: Sony Discussion
Last Post: xSicKxBot

» Replies: 0
» Views: 1
[Steam Release] Cowbots a...
Forum: New Game Releases
Last Post: xSicKxBot

» Replies: 0
» Views: 11
[Dev News] September Free...
Forum: Game Development
Last Post: xSicKxBot

» Replies: 0
» Views: 10
Marvel Rivals Venom guide...
Forum: PC Discussion
Last Post: xSicKxBot

» Replies: 0
» Views: 14
[WoW Retail News] Midnigh...
Forum: World of Warcraft
Last Post: xSicKxBot

» Replies: 0
» Views: 18
[Steam Release] Kodon
Forum: New Game Releases
Last Post: xSicKxBot

» Replies: 0
» Views: 20
[WoW Retail News] Downloa...
Forum: World of Warcraft
Last Post: xSicKxBot

» Replies: 0
» Views: 18
[PS.Blog] (For Southeast ...
Forum: Sony Discussion
Last Post: xSicKxBot

» Replies: 0
» Views: 16
[Steam Release] RAILGRADE...
Forum: New Game Releases
Last Post: xSicKxBot

» Replies: 0
» Views: 24
Fortnite Winterfest 2024 ...
Forum: PC Discussion
Last Post: xSicKxBot

» Replies: 0
» Views: 20

 
  [Tut] PHP Array to JSON String Convert with Online Demo
Posted by: xSicKxBot - 10-23-2022, 01:45 AM - Forum: PHP Development - No Replies

PHP Array to JSON String Convert with Online Demo

by Vincy. Last modified on October 22nd, 2022.

JSON is the best format to transfer data over network. It is an easily parsable format comparatively. That’s why most of the API accepts parameters and returns responses in JSON.

There are online tools to convert an array to a JSON object. This tutorial teaches how to create a program to convert various types of PHP array input into a JSON format.

It has 4 different examples for converting a PHP array to JSON. Those are too tiny in purpose to let beginners understand this concept easily.

Quick example


This quick example is simply coded with a three-line straightforward solution. It takes a single-dimensional PHP array and converts it to JSON.

<?php
$array = array(100, 250, 375, 400);
$jsonString = json_encode($array);
echo $jsonString;
?>

View Demo

The other different array-to-JSON examples handle simple to complex array conversion. It also applies pre-modification (like array mapping) before conversion. The four examples are,

  1. Simple to complex PHP array to JSON.
  2. Remove array keys before converting to JSON.
  3. Convert PHP array with accented characters to JSON
  4. PHP Array to JSON with pretty-printing

If you want the code for the reverse to decode JSON objects to an array, then the linked article has examples.

See this online demo to convert an array of comma-separated values into a JSON object.

php array to json

1) Simple to complex PHP array to JSON


This code handles 3 types of array data into a JSON object. In PHP, it is very easy to convert an array to JSON.

It is a one-line code by using the PHP json_encode() function.

<?php
// PHP Array to JSON string conversion for
// simple, associative and multidimensional arrays
// all works the same way using json_encode
// just present different arrays for example purposes only // simple PHP Array to JSON string
echo '<h1>PHP Array to JSON</h1>';
$array = array( 100, 250, 375, 400
);
$jsonString = json_encode($array);
echo $jsonString; // Associative Array to JSON
echo '<h2>Associative PHP Array to JSON</h2>';
$array = array( 'e1' => 1000, 'e2' => 1500, 'e3' => 2000, 'e4' => 2350, 'e5' => 3000
);
$jsonString = json_encode($array);
echo $jsonString; // multidimensional PHP Array to JSON string
echo '<h2>Multidimensional PHP Array to JSON</h2>';
$multiArray = array( 'a1' => array( 'item_id' => 1, 'name' => 'Lion', 'type' => 'Wild', 'location' => 'Zoo' ), 'a2' => array( 'item_id' => 2, 'name' => 'Cat', 'type' => 'Domestic', 'location' => 'Home' )
);
echo json_encode($multiArray);
?>

Output:

//PHP Array to JSON
[100,250,375,400] //Associative PHP Array to JSON
{"e1":1000,"e2":1500,"e3":2000,"e4":2350,"e5":3000} //Multidimensional PHP Array to JSON
{"a1":{"item_id":1,"name":"Lion","type":"Wild","location":"Zoo"},"a2":{"item_id":2,"name":"Cat","type":"Domestic","location":"Home"}}

2) Remove array keys before converting to JSON


This code handles a different scenario of JSON conversion which must be helpful if needed. For example, if the array associates subject=>marks and the user needs only the marks to plot it in a graph.

It removes the user-defined keys from an associative array and applies json_encode to convert it. It is a two-step process.

  1. It applies PHP array_values() to read the value array.
  2. Then, it applies json_encode on the values array.
<?php
// array_values() to remove assigned keys and convert to the original PHP Array key
echo '<h1>To remove assigned associative keys and PHP Array to JSON</h1>';
$array = array( 'e1' => 1000, 'e2' => 1500, 'e3' => 2000, 'e4' => 2350, 'e5' => 3000
); $jsonString = json_encode(array_values($array));
echo $jsonString;
?>

Output:

[1000,1500,2000,2350,3000]

3) Convert the PHP array with accented characters to JSON


It is also a two-step process to convert the array of data containing accented characters.

It applies UTF8 encoding on the array values before converting them into a JSON object.

For encoding all the elements of the given array, it maps the utf8_encode() as a callback using the PHP array_map() function.

We have seen PHP array functions that are frequently used while working with arrays.

<?php
// Accented characters
// to preserve accented characters during PHP Array to JSON conversion
// you need to utf8 encode the values and then do json_encode
echo '<h1>For accented characters PHP Array to JSON</h1>';
$array = array( 'w1' => 'résumé', 'w2' => 'château', 'w3' => 'façade', 'w4' => 'déjà vu', 'w5' => 'São Paulo'
);
$utfEncodedArray = array_map("utf8_encode", $array);
echo json_encode($utfEncodedArray);
?>

Output:

{"w1":"r\u00c3\u00a9sum\u00c3\u00a9","w2":"ch\u00c3\u00a2teau","w3":"fa\u00c3\u00a7ade","w4":"d\u00c3\u00a9j\u00c3\u00a0 vu","w5":"S\u00c3\u00a3o Paulo"}

4) PHP Array to JSON with pretty-printing


It applies to prettyprint on the converted output JSON properties in a neet spacious format.

The PHP json_encode() function accepts the second parameter to set the bitmask flag. This flag is used to set the JSON_PRETTY_PRINT to align the output JSON properties.

<?php
// to neatly align the output with spaces
// it may be useful when you plan to print the
// JSON output in a raw format
// helpful when debugging complex multidimensional PHP Arrays and JSON objects
// lot more constants are available like this, which might be handy in situations
echo '<h1>Convert PHP Array to JSON and Pretty Print</h1>';
$array = array( 'e1' => 1000, 'e2' => 1500, 'e3' => 2000, 'e4' => 2350, 'e5' => 3000
);
echo json_encode($array, JSON_PRETTY_PRINT);
?>

Output:

{ "e1": 1000, "e2": 1500, "e3": 2000, "e4": 2350, "e5": 3000 }

Download

↑ Back to Top



https://www.sickgaming.net/blog/2022/10/...line-demo/

Print this item

  (Indie Deal) Anime Twilight Bundle, Overcooked, DragonBall
Posted by: xSicKxBot - 10-23-2022, 01:45 AM - Forum: Deals or Specials - No Replies

Anime Twilight Bundle, Overcooked, DragonBall

Anime Twilight Bundle | 6 Steam Games | 93% OFF
[www.indiegala.com]
A new day, a new opportunity to explore the vast anime universe through videogames with a fresh new selection of titles: Project Heartbeat, Skautfold: Usurper, Jester / King, Neko Journey, My Inner Darkness Is A Hot Anime Girl!, Twilight Town: A Cyberpunk Day In Life.

https://www.youtube.com/watch?v=jWSefHXCJY4
[www.indiegala.com]
Plug In Digital Sale & more, up to 90% OFF
New Release: Sunday Gold
[www.indiegala.com]
https://www.youtube.com/watch?v=pgcq-ssK1r8


https://steamcommunity.com/groups/indieg...5717406678

Print this item

  News - Kerbal Space Program 2 Blasts Off Into Early Access February 2023
Posted by: xSicKxBot - 10-23-2022, 01:45 AM - Forum: Lounge - No Replies

Kerbal Space Program 2 Blasts Off Into Early Access February 2023

Kerbal Space Program 2 is finally releasing into early access February 24 next year, after experiencing numerous delays.

The sequel to the 2015 space flight simulator was meant to launch in early 2021, but was delayed, then delayed again to 2022, and finally a third time to 2023. But a specific date is now locked in, with players able to dig into the game on PC via Steam or the Epic Games Store early next year.

Developer Intercept Games released a 14-minute-long video going into some more detail about the game, announcing the early access release, and explaining why it's decided to take this route. "I cannot overstate how important it is for me to hear what people think about this thing we're creating," explained creative director Nate Simpson. "We've been working in a vacuum for quite a while, this is a rare opportunity to actually find out how we've been doing."

Continue Reading at GameSpot

https://www.gamespot.com/articles/kerbal...01-10abi2f

Print this item

  PC - The Last Oricru
Posted by: xSicKxBot - 10-23-2022, 01:45 AM - Forum: New Game Releases - No Replies

The Last Oricru



The Last Oricru is a story-driven action RPG, that puts you in the middle of an ongoing conflict between two races, on a partly terraformed planet, isolated from outer space by a protective barrier. Your decisions will bring interesting twists into the gameplay, as you can heavily influence the conflict and its outcome. You will experience hundreds of intense fights in a brutal medieval meets sci-fi world, where every decision has its consequences.

Level up your hero, improve your skills before facing one of many boss fights and get ready for an unprecedented amount of possibilities.

Publisher: Prime Matter

Release Date: Oct 13, 2022




https://www.metacritic.com/game/pc/the-last-oricru

Print this item

  [Tut] Python | Split String into Characters
Posted by: xSicKxBot - 10-22-2022, 02:35 AM - Forum: Python - No Replies

Python | Split String into Characters

Rate this post

Summary: Use the list("given string") to extract each character of the given string and store them as individual items in a list.
Minimal Example:
print(list("abc"))

Problem: Given a string; How will you split the string into a list of characters?

Example: Let’s visualize the problem with the help of an example:


input = “finxter”
output = [‘f’, ‘i’, ‘n’, ‘x’, ‘t’, ‘e’, ‘r’]

Now that we have an overview of our problem let us dive into the solutions without further ado.

Method 1: Using The list Constructor


Approach: One of the simplest ways to solve the given problem is to use the list constructor and pass the given string into it as the input.

list() creates a new list object that contains items obtained by iterating over the input iterable. Since a string is an iterable formed by combining a group of characters, hence, iterating over it using the list constructor yields a single character at each iteration which represents individual items in the newly formed list.

Code:

text = "finxter"
print(list(text)) # ['f', 'i', 'n', 'x', 't', 'e', 'r']

?Related Tutorial: Python list() — A Simple Guide with Video

Method 2: Using a List Comprehension


Another way to split the given string into characters would be to use a list comprehension such that the list comprehension returns a new list containing each character of the given string as individual items.

Code:

text = "finxter"
print([x for x in text]) # ['f', 'i', 'n', 'x', 't', 'e', 'r']

Prerequisite: To understand what happened in the above code, it is essential to know what a list comprehension does. In simple words, a list comprehension in Python is a compact way of creating lists. The simple formula is [expression + context], where the “expression” determines what to do with each list element. And the “context” determines what elements to select. The context can consist of an arbitrary number of for and if statements. To learn more about list comprehensions, head on to this detailed guide on list comprehensions.

Explanation: Well! Now that you know what list comprehensions are, let’s try to understand what the above code does. In our solution, the context variable x is used to extract each character from the given string by iterating across each character of the string one by one with the help of a for loop. This context variable x also happens to be the expression of our list comprehension as it stores the individual characters of the given string as separate items in the newly formed list.

Multi-line Solution: Another approach to formulating the above solution is to use a for loop. The idea is pretty similar; however, we will not be using a list comprehension in this case. Instead, we will use a for loop to iterate across individual characters of the given string and store them one by one in a new list with the help of the append method.

text = "finxter"
res = []
for i in text: res.append(i)
print(res) # ['f', 'i', 'n', 'x', 't', 'e', 'r']

Method 3: Using map and lambda


Yet another way of solving the given problem is to use a lambda function within the map function. Now, this is complex and certainly not the best fit solution to the given problem. However, it may (or may not ;P) be appropriate when you are handling really complex tasks. So, here’s how to use the two built-in Python functions to solve the given problem:

import re
text = "finxter"
print(list(map(lambda c: c, text))) # ['f', 'i', 'n', 'x', 't', 'e', 'r']

Explanation: The map() function is used to execute a specified function for each item of an iterable. In this case, the iterable is the given string and each character of the string represents an individual item within it. Now, all we need to do is to create a lambda function that simply returns the character passed to it as the input. That’s it! However, the map method will return a map object, so you must convert it to a list using the list() function. Silly! Isn’t it? Nevertheless, it works!

Conclusion


Hurrah! We have successfully solved the given problem using as many as three different ways. I hope you enjoyed this article and it helps you in your Python coding journey. Please subscribe and stay tuned for more interesting articles!

Related Reads:
⦿ How To Split A String And Keep The Separators?
⦿
How To Cut A String In Python?




https://www.sickgaming.net/blog/2022/10/...haracters/

Print this item

  (Indie Deal) Scorn is out & FREE GRANDPA! RUN!
Posted by: xSicKxBot - 10-22-2022, 02:35 AM - Forum: Deals or Specials - No Replies

Scorn is out & FREE GRANDPA! RUN!

RUN! GRANDPA! RUN! FREEbie
[freebies.indiegala.com]
Strap in for an epic adventure for freedom in a rocket-powered wheelchair.

https://youtu.be/CNDaMRvPTGU
WayForward Sale, up to 60% OFF & more
[www.indiegala.com]
https://www.youtube.com/watch?v=vsEjnSl0oWQ


https://steamcommunity.com/groups/indieg...8893448355

Print this item

  PC - LEGO Bricktales
Posted by: xSicKxBot - 10-22-2022, 02:35 AM - Forum: New Game Releases - No Replies

LEGO Bricktales



Your grandfather, a genius inventor, has called you for help! His beloved amusement park is about to close as the mayor is threatening to shut everything down and seize the land if the necessary repairs aren't made to bring it up to code. With the help of your powerful little robot buddy, you can restore it using a mysterious device based on alien technology.

As a source of power, the device needs happiness crystals, which you can harvest by making people happy and solving their problems. With the aid of a portal, travel to different locations all around the world to help people and collect their happiness crystals.

Strap in for the ultimate building adventure and save your grandfather's amusement park!

In this puzzle-adventure, use an intuitive brick-by-brick building mechanic to solve puzzles and bring your creations to life! Experience a charming story as you explore beautiful LEGO dioramas and help the people inhabiting them.

Publisher: Thunderful

Release Date: Oct 12, 2022




https://www.metacritic.com/game/pc/lego-bricktales

Print this item

  News - The Best Metal Gear Games, Ranked
Posted by: xSicKxBot - 10-22-2022, 02:35 AM - Forum: Lounge - No Replies

The Best Metal Gear Games, Ranked

Few video game franchises have been as revolutionary as Metal Gear over the decades, a series that has consistently reinvented itself to offer fresh and exciting twists on tactical espionage action. From the original game that prioritized stealth in an era where action games ruled supreme, to the groundbreaking rebirth of the series that paved the way for cinematic video games, the brainchild of Hideo Kojima has never been short on surprises.

35 years later, the Metal Gear series is a legendary showcase of creative design, intense showdowns, and storylines that helped prove that video games could be cinematic powerhouses. Grab your favorite cardboard box, sneak in for a covert op, and grab some intel on the best Metal Gear Solid games to make the cut in GameSpot's list. Our list is organized from worst to best. We excluded a couple of mobile games and the non-canon Snake's Revenge, but almost the entire franchise is represented here.

For more game rankings, you can check out our features on the best Final Fantasy, Lord of the Rings, and Pokemon games.

Continue Reading at GameSpot

https://www.gamespot.com/articles/the-be...01-10abi2f

Print this item

  [Oracle Blog] Announcing GraalVM Enterprise 22.3
Posted by: xSicKxBot - 10-21-2022, 09:47 AM - Forum: Java Language, JVM, and the JRE - No Replies

Announcing GraalVM Enterprise 22.3

The GraalVM 22.3 release delivers several new features including much anticipated support for Java 19 along with preview support for Project Loom virtual threads in both JVM JIT and Native Image ahead-of-time compiled applications. The release also includes compiler performance improvements, new monitoring and debugging features in Native Image, Python enhancements, and a new name for GraalPython!

https://blogs.oracle.com/java/post/annou...rprise-223

Print this item

  [Tut] How to Return a File From a Function in Python?
Posted by: xSicKxBot - 10-21-2022, 09:47 AM - Forum: Python - No Replies

How to Return a File From a Function in Python?

5/5 – (1 vote)

Do you need to create a function that returns a file but you don’t know how? No worries, in sixty seconds, you’ll know! Go! ?

A Python function can return any object such as a file object. To return a file, first open the file object within the function body, handle all possible errors if the file doesn’t exist, and return it to the caller of the function using the keyword operation return open(filename, mode='r').

Here’s a minimal example that tries to open a filename that was provided by the user via the input() function. If it fails, it prints an error message and asks for a different user input:

def open_file(): while True: filename = input('filename: ') try: return open(filename, mode='r') except: print('Error. Try again') f = open_file()
print(f.read())

If I type in the correct file right away, I get the following output when storing the previous code snippet in a file named code.py—the code reads itself (meta ?):

filename: code.py
def open_file(): while True: filename = input('filename: ') try: return open(filename, mode='r') except: print('Error. Try again') f = open_file()
print(f.read())

Note that you can open the file in writing mode rather than reading mode by replacing the line with the return statement with the following line:

open(filename, mode='w')

A more Pythonic way, in my opinion, is to follow the single-responsibility pattern whereby a function should do only one thing. In that case, provide the relevant input values into the function like so:

def open_file(filename, mode): try: return open(filename, mode=mode) except: return None def ask_user(): f = open_file(input('filename: '), input('mode: ')) while not f: f = open_file(input('filename: '), input('mode: ')) return f f = ask_user() print(f.read()) 

Notice how the file handling of a single instance and the user input processing are separated into two functions. Each function does one thing only. Unix style.


If you want to improve your programming skills and coding productivity creating massive success with your apps and coding projects, feel free to check out my book on the topic:


The Art of Clean Code



Most software developers waste thousands of hours working with overly complex code. The eight core principles in The Art of Clean Coding will teach you how to write clear, maintainable code without compromising functionality. The book’s guiding principle is simplicity: reduce and simplify, then reinvest energy in the important parts to save you countless hours and ease the often onerous task of code maintenance.

  1. Concentrate on the important stuff with the 80/20 principle — focus on the 20% of your code that matters most
  2. Avoid coding in isolation: create a minimum viable product to get early feedback
  3. Write code cleanly and simply to eliminate clutter
  4. Avoid premature optimization that risks over-complicating code
  5. Balance your goals, capacity, and feedback to achieve the productive state of Flow
  6. Apply the Do One Thing Well philosophy to vastly improve functionality
  7. Design efficient user interfaces with the Less is More principle
  8. Tie your new skills together into one unifying principle: Focus

The Python-based The Art of Clean Coding is suitable for programmers at any level, with ideas presented in a language-agnostic manner.


Related Tutorials


Programmer Humor


Q: How do you tell an introverted computer scientist from an extroverted computer scientist? A: An extroverted computer scientist looks at your shoes when he talks to you.


https://www.sickgaming.net/blog/2022/10/...in-python/

Print this item