How to push array with key? - php

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)

Related

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

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

Split array into key => array()

Consider the following array:
$array[23] = array(
[0] => 'FOO'
[1] => 'BAR'
[2] => 'BAZ'
);
Whenever I want to work with the inner array, I do something like this:
foreach ($array as $key => $values) {
foreach ($values as $value) {
echo $value;
}
}
The outer foreach-loop is there to split the $key and $value-pairs of $array. This works fine for arrays with many keys ([23], [24], ...)but seems redundant if you know beforehand that $array only has one key (23 in this case). In a case as such, isn't there a better way to split the key from the values? Something like
split($array into $key => $values)
foreach ($values as $value) {
echo $value;
}
I hope I made myself clear.
reset returns the first element of you array and key returns its key:
$your_inner_arr = reset($array);
$your_key = key($array);
Yea, just get rid of your first foreach and define the array you're using with the known $key of your outter array.
foreach ($array[23] as $key =>$val):
//do whatever you want in here
endforeach;
If an array has only one element, you can get it with reset:
$ar = array(23 => array('foo', 'bar'));
$firstElement = reset($ar);
A very succinct approach would be
foreach(array_shift($array) as $item) {
echo $item;
}

PHP rename array keys in multidimensional array

In an array such as the one below, how could I rename "fee_id" to "id"?
Array
(
[0] => Array
(
[fee_id] => 15
[fee_amount] => 308.5
[year] => 2009
)
[1] => Array
(
[fee_id] => 14
[fee_amount] => 308.5
[year] => 2009
)
)
foreach ( $array as $k=>$v )
{
$array[$k] ['id'] = $array[$k] ['fee_id'];
unset($array[$k]['fee_id']);
}
This should work
You could use array_map() to do it.
$myarray = array_map(function($tag) {
return array(
'id' => $tag['fee_id'],
'fee_amount' => $tag['fee_amount'],
'year' => $tag['year']
); }, $myarray);
$arrayNum = count($theArray);
for( $i = 0 ; $i < $arrayNum ; $i++ )
{
$fee_id_value = $theArray[$i]['fee_id'];
unset($theArray[$i]['fee_id']);
$theArray[$i]['id'] = $fee_id_value;
}
This should work.
Copy the current 'fee_id' value to a new key named 'id' and unset the previous key?
foreach ($array as $arr)
{
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
There is no function builtin doing such thin afaik.
This is the working solution, i tested it.
foreach ($myArray as &$arr) {
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
The snippet below will rename an associative array key while preserving order (sometimes... we must). You can substitute the new key's $value if you need to wholly replace an item.
$old_key = "key_to_replace";
$new_key = "my_new_key";
$intermediate_array = array();
while (list($key, $value) = each($original_array)) {
if ($key == $old_key) {
$intermediate_array[$new_key] = $value;
}
else {
$intermediate_array[$key] = $value;
}
}
$original_array = $intermediate_array;
Converted 0->feild0, 1->field1,2->field2....
This is just one example in which i get comma separated value in string and convert it into multidimensional array and then using foreach loop i changed key value of array
<?php
$str = "abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu;
echo '<pre>';
$arr1 = explode("\n", $str); // this will create multidimensional array from upper string
//print_r($arr1);
foreach ($arr1 as $key => $value) {
$arr2[] = explode(",", $value);
foreach ($arr2 as $key1 => $value1) {
$i =0;
foreach ($value1 as $key2 => $value2) {
$key3 = 'field'.$i;
$i++;
$value1[$key3] = $value2;
unset($value1[$key2]);
}
}
$arr3[] = $value1;
}
print_r($arr3);
?>
I wrote a function to do it using objects or arrays (single or multidimensional) see at https://github.com/joaorito/php_RenameKeys.
Bellow is a simple example, you can use a json feature combine with replace to do it.
// Your original array (single or multi)
$original = array(
'DataHora' => date('YmdHis'),
'Produto' => 'Produto 1',
'Preco' => 10.00,
'Quant' => 2);
// Your map of key to change
$map = array(
'DataHora' => 'Date',
'Produto' => 'Product',
'Preco' => 'Price',
'Quant' => 'Amount');
$temp_array = json_encode($original);
foreach ($map AS $k=>$v) {
$temp_array = str_ireplace('"'.$k.'":','"'.$v.'":', $temp);
}
$new_array = json_decode($temp, $array);
Multidimentional array key can be changed dynamically by following function:
function change_key(array $arr, $keySetOrCallBack = [])
{
$newArr = [];
foreach ($arr as $k => $v) {
if (is_callable($keySetOrCallBack)) {
$key = call_user_func_array($keySetOrCallBack, [$k, $v]);
} else {
$key = $keySetOrCallBack[$k] ?? $k;
}
$newArr[$key] = is_array($v) ? array_change_key($v, $keySetOrCallBack) : $v;
}
return $newArr;
}
Sample Example:
$sampleArray = [
'hello' => 'world',
'nested' => ['hello' => 'John']
];
//Change by difined key set
$outputArray = change_key($sampleArray, ['hello' => 'hi']);
//Output Array: ['hi' => 'world', 'nested' => ['hi' => 'John']];
//Change by callback
$outputArray = change_key($sampleArray, function($key, $value) {
return ucwords(key);
});
//Output Array: ['Hello' => 'world', 'Nested' => ['Hello' => 'John']];
I have been trying to solve this issue for a couple hours using recursive functions, but finally I realized that we don't need recursion at all. Below is my approach.
$search = array('key1','key2','key3');
$replace = array('newkey1','newkey2','newkey3');
$resArray = str_replace($search,$replace,json_encode($array));
$res = json_decode($resArray);
On this way we can avoid loop and recursion.
Hope It helps.

Categories