Get value from multiple dimension associative array in Php - php

I have a POST request array that looks like this
$request = array (size=2)
'licence' => string 'uDyQwFwqV7aQG2z' (length=15)
'user' =>
array (size=7)
'first_name' => string 'Danut' (length=5)
'last_name' => string 'Florian' (length=7)
'username' => string 'daniesy9' (length=8)
'password' => string '123456' (length=6)
'rpassword' => string '123456' (length=6)
'email' => string 'daniesy+1#me.com' (length=16)
'phone' => string '9903131' (length=7)
This in fact is an array which represents values sent by a form. I know the name of the elements, for example the username input has the name of user[username] and i have to find the related value from the array, by name. Something like:
$key = "user[username]";
$request[key];
Any idea how to do this?
I know that the correct way to do it is $request["user"]["username"] but it's quite complicated because i have to use the fields names from the form which are user[username], user[firstname], etc and it might have up to 4 levels of depth.

Answered in comments but similar Question to
Convert a String to Variable
eval('$username = $request["user"]["username"];');
Edit
Eval not a valid suggestion as request data.
So I would suggest the second method on this post
<?php
$request = array(
'user' => array(
'username' => 'joe_blogs'
)
);
function extract_data($string) {
global $request;
$found_matches = preg_match_all('/\[\"([a-z]+)\"\]/', $string, $matches);
if (!$found_matches) {
return null;
}
$current_data = $request;
foreach ($matches[1] as $name) {
if (key_exists($name, $current_data)) {
$current_data = $current_data[$name];
} else {
return null;
}
}
return $current_data;
}
$username = extract_data('request["user"]["username"]');
?>

function findInDepth($keys, $array){
$key = array_shift($keys);
if(!isset($array[$key])){
return FALSE;
}
if(is_array($array[$key])){
return findInDepth($keys, $array[$key]);
}
return $array[$key];
}
$key = "user[username]";
$keys = preg_split("/(\[|\])/", $key);
echo findInDepth($keys, $request);
This function solves my problem. It first splits the string (aka the input name) into an array of keys and then recessively searches in depth the array by keys until it finds a value which is not an array and returns FALSE otherwise.

You could separate keys with dots. Primitive example:
<?php
class ArrayDot
{
protected $array = [];
public function __construct(array $array) {$this->array = $array;}
public function get($path)
{
$array = $this->array;
foreach(explode('.', $path) as $key) {
$array = $array[$key];
}
return $array;
}
}
$array = [
'user' => [
'username' => 'tootski',
]
];
$a = new ArrayDot($array);
echo $a->get('user.username'); # tootski

Related

I can not get selection input with string keys

In laravel 8 app with laravelcollective/html 6.2 and php7.4 I need to fill selection input with method in model :
private static $userStatusLabelValueArray = ['N' => 'New(Waiting activation)', 'A' => 'Active', 'I' => 'Inactive', 'B'=>'Banned'];
public static function getUserStatusValueArray($key_return = true): array
{
$resArray = [];
foreach (self::$userStatusLabelValueArray as $key => $value) {
echo '<pre>$key::'.print_r($key,true).'</pre>';
echo '<pre>$value::'.print_r($value,true).'</pre>';
if ($key_return) {
$resArray[] = ['key' => $key, 'label' => $value];
} else {
$resArray[$key] = $value;
}
}
return $resArray;
}
debugging I see that $key has valid string value but when $key_return is false I got array with
keys 0...3, not 'N', 'A' as I expected.
Which way is valid ?
Thanks!

How to convert array to multidimensional array with special keys using php?

I have an array
$array = [
0=>1
1=>Jon
2=>jon#email.com
3=>2
4=>Doe
5=>doe#email.com
6=>3
7=>Foo
8=>foo#email.com
]
What I`d like to do is to add and extra value to each value.
Something like this so I can access it when looping through the array
$array=[
0=>1[id]
1=>Jon[name]
2=>jon#email.com[email]
3=>2[id]
4=>Doe[name]
5=>doe#email.com[email]
6=>3[id]
7=>Foo[name]
8=>foo#email.com[email]
]
I guess it would be a multidimensional array?
What would be the proper way of doing it?
Loop through array and check key of items and based of it create new array and insert values in it.
$newArr = [];
foreach($array as $key=>$value){
if ($key % 3 == 0)
$newArr[] = ["id" => $value];
if ($key % 3 == 1)
$newArr[sizeof($newArr)-1]["name"] = $value;
if ($key % 3 == 2)
$newArr[sizeof($newArr)-1]["email"] = $value;
}
Check result in demo
yes just use 2 dimension array
$arr = array();
$arr[0][0] = "1"
$arr[0][1] = "Jon"
$arr[0][2] = "jon#email.com"
$arr[1][0] = "2"
$arr[1][1] = "Doe"
$arr[1][2] = "doe#email.com"
Since an array is a map in PHP, I'd recommend to use it like a map or to create a class holding the data.
$arr = array();
$arr[0]['ID'] = 1;
$arr[0]['name'] = "John";
$arr[0]['mail'] = "john#email.com;
Example for one class:
<?PHP
class User
{
public $id;
public $name;
public $mail;
function __construct($ID,$name,$mail)
{
$this->id = $ID;
$this->name = $name;
$this->mail = $mail;
}
}
?>
and then you can simply use it like that:
<?PHP
require_once("User.php");
$user = new User(1,"Mario","maio290#foo.bar");
echo $user->name;
?>
A simple, yet often-used solution is to use multidimensional array with string keys for better readability:
$array = [
0 => [
'id' => 1,
'name' => 'Jon',
'email' => 'jon#email.com',
],
1 => [
'id' => 2,
'name' => 'Doe',
'email' => 'doe#email.com',
],
2 => [
'id' => 3,
'name' => 'Foo',
'email' => 'foo#email.com',
],
];
You can loop through this like so:
for ($array as $item) {
// $item['id']
// $item['name']
// $item['email']
}
But since PHP is an object-oriented language, I'd suggest creating a class for the data-structure. This is even easier to read and you can very easily add functionality related to the entity etc.
class Person {
public $id;
public $name;
public $email;
function __construct($id, $name, $email) {
$this->id = $id;
$this->name = $name;
$this->email = $email;
}
}
$array = [
0 => new Person(1, 'Jon', 'jon#email.com'),
1 => new Person(2, 'Doe', 'doe#email.com'),
2 => new Person(3, 'Foo', 'foo#email.com'),
];
You can loop through this like so:
for ($array as $person) {
// $person->id
// $person->name
// $person->email
}
Use array_map on the result of array_chunck this way:
$array=array_map(function($val){ return array_combine(['id','name','email'],$val);}, array_chunk($array,3));
note that the second parameter of array_chunk depend of the number of columns and the first array used in array_combine too
see the working code here
You can also do like this:
$array1 = ["name"=>"alaex","class"=>4];
$array2 = ["name"=>"aley","class"=>10];
$array3 = ["student"=>$array1,"student2"=>$array2];
print_r($array3);

PHP: Replace Array Data

I have an array of associative array, I will like to update the values in this array, hence I created a function that looks like this.
//The Array of Associative arrays
array (size=2)
0 =>
array (size=3)
'slang' => string 'Tight' (length=5)
'description' => string 'Means well done' (length=15)
'example-sentence' => string 'Prosper it Tight on that job' (length=28)
1 =>
array (size=3)
'slang' => string 'Sleet' (length=5)
'description' => string 'Means to send on long errand' (length=28)
'example-sentence' => string 'I am going to sleep sia' (length=23)
//The function
public function update($slang, $new)
{
array_map(function($data, $key) use($slang, $new)
{
if($data['slang'] == $slang)
{
$data[$key] = array_replace($data, $new);
}
}, UrbanWord::$data);
}
I tired running this but the original array will not update. I need help on how to go about fixing this please.
Thanks
You may use array_reduce instead of array_map as following:
public function update($array, $slang, $new)
{
return array_reduce($array, function ($result, $item) use ($slang, $new) {
if ($item['slang'] == $slang) {
$item = array_replace($item, $new);
}
$result[] = $item;
return $result;
}, array());
}
Usage:
UrbanWord::$data = $this->update(
UrbanWord::$data,
'Tight',
array('description' => 'another description')
);
var_dump($myUpdatedArray);
If you want to update it directly passing the UrbanWord::$data by reference you may try something like:
class UrbanWord
{
public static $data = array(
array(
'slang' => 'Test',
'Desc' => 'Frist Desc'
),
array(
'slang' => 'Test1',
'Desc' => 'Second Desc'
)
);
}
class MyClass
{
public function update(&$array, $slang, $new)
{
$array = array_reduce($array, function ($result, $item) use ($slang, $new) {
if ($item['slang'] == $slang) {
$item = array_replace($item, $new);
}
$result[] = $item;
return $result;
}, array());
}
}
$myClass = new MyClass();
$myClass->update(UrbanWord::$data, 'Test', array('Desc' => 'test'));
echo '<pre>';
var_dump(UrbanWord::$data);
echo '</pre>';

Get the element with array and object

I spent over 2 hours looking for the solution, and I leave it to you because I am completely blocked. I try to learn the object in PHP. I created a function that return me the result of an SQL query.
Here is the var_dump return :
object(stdClass)[6]
public 'name' =>
array (size=2)
0 =>
object(stdClass)[11]
public 'id' => string '1' (length=1)
1 =>
object(stdClass)[12]
public 'id' => string '5' (length=1)
I used a foreach to parse this, but I don't get directly the id of each element. And I especially don't want to use another foreach.
foreach($function as $key => $value){
var_dump($value->id);
}
But it doesn't work there.
Here is the function called who returns this result
public function nameFunction () {
$obj = new stdClass();
$return = array();
$request = $this->getConnexion()->prepare('SELECT id FROM table') or die(mysqli_error($this->getConnexion()));
$request->execute();
$request->store_result();
$request->bind_result($id);
while ($request->fetch()) {
$return[] = parent::parentFunction($id);
}
$obj->name = $return;
$request-> close();
return $obj;
}
And parent::parentFunction($id) returns :
object(stdClass)[11]
public 'id' => string '1' (length=1)
You are looping the object instead of array. Try to use this code
foreach($function->name as $key => $value){
var_dump($value->id);
}
Tell me if it works for you
This question might help you :
php parsing multidimensional stdclass object with arrays
Especially answer from stasgrin
function loop($input)
{
foreach ($input as $value)
{
if (is_array($value) || is_object($value))
loop($value);
else
{
//store data
echo $value;
}
}
}

Create nested arrays from specific variables within session

I have several values stored in $_SESSION beginning with 'first_name_' & 'last_name_' which then a number appended to the end deepening on how many names are generated.
I am able to extract each of these values from the session and add to an array but would like to pair up the first and last names together within a nested array. (if that makes sense)
at the moment I have:
$users_array = array();
foreach ($_SESSION as $key => $value) {
if(strpos($key, 'first_name_') === 0) {
$users_array[] = $value;
}
if(strpos($key, 'last_name_') === 0) {
$users_array[] = $value;
}
}
This produces an output with var_dump:
array
0 => string 'John' (length=4)
1 => string 'Smith' (length=8)
2 => string 'Jane' (length=4)
3 => string 'Doe' (length=3)
But what I would like is something like:
array
'user' =>
array
'first_name' => string 'John' (length=4)
'last_name' => string 'Smith' (length=5)
array
'first_name' => string 'Jane' (length=4)
'last_name' => string 'Doe' (length=5)
Any suggestions on how I can achieve this?
deceze is right in his comment... But just so people with similar issues with creating 2-dimensional array from a 1-dimensional array, here is a solution. Also, note that PHP does not guarantee that the order will be same when iterating using FOREACH. As this will work, it is still prone to errors.
$users_array = array();
foreach ($_SESSION as $key => $value) {
if(strpos($key, 'first_name_') === 0) {
$users_array[] = array();
$users_array[count($users_array)-1]['first_name'] = $value;
}
if(strpos($key, 'last_name_') === 0) {
$users_array[count($users_array)-1]['last_name'] = $value;
}
}

Categories