Restructure an array - php

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

Related

How to push array with key?

I want do like this:
$m_array = array();
foreach ($values as $key) { <- $key is just string
array_push ( $m_array, $key => array() );
}
/////result
$m_array = array(
"key1" => array(),
"key2" => array(),
....
);
How to do this?
Please help me.
I use PHP.
You don't need to use array_push to append to arrays. array_push is the same as $array[] = $val.
In your case you want to specify keys:
$m_array = array();
foreach ($values as $key) { <- $key is just string
$m_array[$key] = array();
}
Note that array_push does have a use if you want to push more than one value at once because you can do something like this:
array_push($array, $value1, $value2, $value3)

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);

PHP Foreach array in array

I need make array in array. Like this:
$array = array(
array("value" => 1),
array("value2" => 2));
I've tried to code it:
foreach($labels as $stats => $label)
{
$array = array(
array($label, $registrations[$stats])
);
}
But it prints only one array, how to fix it? I know my code is bad, but I'm newbie in PHP :( Or I must use while?
On each iteration you should add new array to a result array:
$array = array();
foreach($labels as $stats => $label)
{
$array[] = array($label, $registrations[$stats]);
}
Or if you want key-value array:
$array = array();
foreach($labels as $stats => $label)
{
$array[$label] = $registrations[$stats];
}

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']
)
);

Output 1 array from 2 different multidimensional arrays in a foreach loop

I need a little help with multidimensional arrays. I need to output/create an new array from two other arrays in PHP. I know that my example is wrong, but here is an example of what I have that almost works:
$myarray = array(
'customid1' = array(
name=> 'Tim',
address=> '23 Some Address'
),
'customid2' = array(
name=> 'John',
address=> 'Another Address'
)
);
$keys = array();
$values = array();
foreach($myarray as $key => $keyitem) {
$getkeys = $myarray[$key]['name'] .'-and-a-string';
$keys[] = $getkeys;
}
foreach($myarray as $value => $valueitem) {
$getvalues = 'some-other-text-'. $myarray[$key]['address'];
$values[] = $getvalues;
}
$newarray = array_combine($keys, $values);
The code above will get all the keys right, except the values for that key inside the new array. Instead it shows the last value in the array in all of keys. So my print_r results will look like:
Array ( Tim-and-a-string => some-other-text-Another Address
John-and-a-string => some-other-text-Another Address
)
As you can see, 'some-other-text-Another Address' appears on all of them, but the second key 'Tim-and-a-string' needs to have 'some-other-text-23 Some Address' included
It's a very minor error but you are using the wrong variable:
You are using $key instead of $value in the second foreach().
$key would be the same as the last key in the loop before since the new foreach loop does not override it.
This should work:
$myarray = array(
'customid1' = array(
name=> 'Tim',
address=> '23 Some Address'
),
'customid2' = array(
name=> 'John',
address=> 'Another Address'
)
);
$keys = array();
$values = array();
foreach($myarray as $key => $keyitem) {
$getkeys = $myarray[$key]['name'] .'-and-a-string';
$keys[] = $getkeys;
}
foreach($myarray as $value => $valueitem) {
$getvalues = 'some-other-text-'. $myarray[$value]['address'];
$values[] = $getvalues;
}
$newarray = array_combine($keys, $values);
Try this:
$newarray = array_combine(
array_values(array_map(function ($v) { return $v['name'].'-and-a-string'; }, $myarray)),
array_values(array_map(function ($v) { return 'some-other-text-'.$v['address']; }, $myarray))
);

Categories