write foreach inside calling class - php

hi im using this php code
$data = new $models([
'number' => $row[0],
'name' => $row[1],
]);
like this its working fine but what i want is that i dont know the keys 'number' and 'name' what if i want them come from array like this ..
$array = ['name','number','anything'];
$data = new $models([
foreach($array as $key => $arr)
{
$arr => $row[$key];
}
]);
how can i do something like this ..
calling foreach inside creating new class ..
thanks ..

<?php
class Foo{}
$className='Foo';
$array = ['name','number','anything'];
$row = ['name_v', 'number_v', 'anything_v'];
$foo = new $className();
foreach(array_combine($array, $row) as $k => $v){
$foo->$k = $v;
}
print(json_encode($foo));

So long as they have the same number of elements in the order that you want, just combine them:
$array = ['name', 'number', 'anything'];
$data = new $models(array_combine($array, $row));
You can do it in one line:
$data = new $models(array_combine(['name', 'number', 'anything'], $row));

Related

Loop over one array as if it was a multidimensional array

I have an array like:
$array = array(
'name' => 'Humphrey',
'email' => 'humphrey#wilkins.com
);
This is retrieved through a function that gets from the database. If there is more than one result retrieved, it looks like:
$array = array(
[0] => array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
[1] => array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
If the second is returned, I can do a simple foreach($array as $key => $person), but if there is only one result returned (the first example), I can't run a foreach on this as I need to access like: $person['name'] within the foreach loop.
Is there any way to make the one result believe its a multidimensional array?
Try this :
if(!is_array($array[0])) {
$new_array[] = $array;
$array = $new_array;
}
I would highly recommended making your data's structure the same regardless of how many elements are returned. It will help log terms and this will have to be done anywhere that function is called which seems like a waste.
You can check if a key exists and do some logic based on that condition.
if(array_key_exists("name", $array){
//There is one result
$array['name']; //...
} else {
//More then one
foreach($array as $k => $v){
//Do logic
}
}
You will have the keys in the first instance in the second yours keys would be the index.
Based on this, try:
function isAssoc(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
if(isAssoc($array)){
$array[] = $array;
}
First check if the array key 'name' exists in the given array.
If it does, then it isn't a multi-dimensional array.
Here's how you can make it multi-dimensional:
if(array_key_exists("name",$array))
{
$array = array($array);
}
Now you can loop through the array assuming it's a multidimensional array.
foreach($array as $key => $person)
{
$name = $person['name'];
echo $name;
}
The reason of this is probably because you use either fetch() or fetchAll() on your db. Anyway there are solutions that uses some tricks like:
$arr = !is_array($arr[0]) ? $arr : $arr[0];
or
is_array($arr[0]) && ($arr = $arr[0]);
but there is other option with array_walk_recursive()
$array = array(
array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
$array2 = array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
);
$print = function ($item, $key) {
echo $key . $item .'<br>';
};
array_walk_recursive($array, $print);
array_walk_recursive($array2, $print);

Restructure an array

I have this array in PHP
$fields = array(
0 => array(
'field1' => 'something1',
'field2' => 'something2'
)
)
And I need it to look like this
$fields = array(
'fields1' => 'something1',
'fields2' => 'something2'
)
What function code can I use to get rid of the 0 index in the example?
You can loop through like this...
Create new array
$newArray = [];
Then loop through
foreach($fields as $field){
if(is_array($field)){
foreach($field as $key => $value){
$newArray[$key] = $value;
}
}
}
just take the '0' element from fields:
$fields=$fields[0];
Simple
$fields = reset($fields);
Or
$fields = array_shift($fields);
Create an array, loop through $fields, and merge whatever items are there with the created array.
$final_array = array();
foreach ($fields as $field)
{
$final_array = array_merge($final_array, $field);
}
$fields = $final_array;
This will be able to handle any number of items in either level of the array and compact them into a one-level array.
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data)); $list = iterator_to_array($it,false);
Use this to get ride of any extra levels.
Will gives you what you want

Access and explode comma-delimited data from multidimensional array then populate a new 2d array

I have a multidimensional array containing comma-separated strings like this
[
[
"users" => [
'email' => 'test#yahoo.com ,testuser#yahoo.com',
'username' => 'test,testuser',
'description' => 'description1,description2'
]
]
]
I want to access the users subarray data, explode on delimiters, and create a new associative array of indexed arrays.
Desired result:
$User = array(
'email' => array(
'test#yahoo.com',
'testuser#yahoo.com'
),
'username' => array(
'test',
'testuser'
),
'description' => array(
'description1',
'description2'
)
);
For only one index:
$arrayTwoD = array();
foreach ($valueMult[0]['User'] as $key => $value) {
$arrayTwoD[$key] = array_push(explode(',', $value));
}
If you have multiple indexes in $multArray:
$arrayTwoD = array();
foreach ($multArray as $keyMult => $valueMult) {
foreach ($valueMult['User'] as $key => $value) {
$arrayTwoD[$keyMult][$key] = array_push(explode(',', $value));
}
}
or
$arrayTwoD = array();
foreach ($multArray as $array) {
foreach ($array['User'] as $key => $value) {
$arrayTwoD[$key] = array_push(explode(',', $value));
}
}
try this
$array = array(...); // your array data
$formedArray = array();
foreach ( $array as $arr )
{
foreach ( $arr['user'] as $key => $value )
{
$formedArray[$key] = array_push(explode(",",$value));
}
}
echo "<pre>";
print_r($formedArray);
echo "</pre>";
It's a little bit repetitive, I know, but you can do like this as well:
foreach($array as $users) {
foreach($users as &$value) { // &value is assigned by reference
$users['users']["email"] = explode(",", $value['email']);
$users['users']["username"] = explode(",", $value['username']);
$users['users']["description"] = explode(",", $value['description']);
}
}
But after that, you need to use $value. Refer to the official PHP manual documentation to know more about what the & symbol does here.
Demo
Using array_map() can be used to access the subset data (without declaring any new variables in the global scope) and make iterate calls of preg_split() to separate the delimited values into subarrays.
Code: (Demo)
var_export(
array_map(
fn($csv) => preg_split('/ ?,/', $csv),
$array[0]['users']
)
);

Hierarchical data into array

I need some logic for the following problem, but can't get my head around it. Basically I have some data like the following array
array(
array('name' => 'Test1',
'hierarchy'=> '1'),
array('name' => 'Test2',
'hierarchy'=> '1.1'),
array('name' => 'Test3',
'hierarchy'=> '1.2'),
array('name' => 'Test4',
'hierarchy'=> '1.2.1')
)
Now I would like to output an array in such a way that
$array[1] = 'Test1';
$array[1][2][1] = 'Test4';
Tried dynamic variable naming and dynamically creating multidimensional arrays, but both dont seem to work.
That's not possible.
For $array[1] = 'Test1'; $array[1] needs to be a string, but for $array[1][2][1] = 'Test4'; it needs to be an array.
You could do something like this:
$array[1]['text'] = 'Test1';
$array[1][2][1]['text'] = 'Test4';
Here's code for that:
$result = array();
foreach ($input as $entry)
{
$path_components = explode('.', $entry['hierarchy']);
$pointer =& $result;
foreach ($path_components as $path_component)
$pointer =& $pointer[$path_component];
$pointer['text'] = $entry['name'];
unset($pointer);
}
If you don't absolutely need an array, you can create a class and extend ArrayClass or if you need only the array access, you can also implement ArrayAccess.
From there, you can parse through your data and return the required values for your application.

PHP transform array from one dimenson to two

some "simple" problem:
I've this array;
$myArray = array(
'FOO',
'BAR,
);
i want :
$mayArray = array(
'FOO' => array(),
'BAR' => array(),
);
in the moment iam doing it with an foreach:
foreach ($myArray as $key => $val) {
$newArray[$val] = array();
}
$myArray = $newArray;
is there an easyer way ? ;-)
The way you have is pretty easy to understand. But you can also do this:
$myArray = array_fill_keys($myArray, array());
Docs here: http://us2.php.net/manual/en/function.array-fill-keys.php
You can use array_fill_keys, here is example:
$myArray = array_fill_keys($myArray, array());

Categories