I want to remove key 0 from parent array and set child array as parent.
Here I will get single value so one array is ok for me.
My current array looks like this
Array
(
[0] => Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
)
I want it like below. expected result
Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
For this I tried like below but no success.
$new = array();
foreach ($data as $v){
$new = array_merge($new , array_values($v)) ;
}
but in my code it's removed key e.g id,api_key, etc....
I need key name also in my new array. please suggest
Remove the array_values
Solution
<?php
$test = array(
array
(
'id' => 3,
'api_key' => 'acount266'
)
);
$new = array();
foreach($test as $v){
$new = array_merge($new, $v);
}
var_dump($new);
Result
array(2) {
["id"]=>
int(3)
["api_key"]=>
string(9) "acount266"
}
According to documentation of PHP as mentioned
reset() function returns the value of the first array element, or
FALSE if the array is empty.
$array = array(
array(
'id' => 3,
'api_key' => 'acount266',
'auth_domain' => 'Tester26',
'database_url' => 'vcc.test.acc+27#gmail.com',
'project_id' => '12345',
'storage_bucket' => '',
'secret_key_path' => '',
'fcm_server_key' => 1,
'messaging_sender_id' => 0,
'key_phrase' => '',
'disable' => 0,
'created' => '',
'updated' => ''
)
);
print_r(reset($test));
I tried this:
$arr = array();
foreach ($examples as $example) {
foreach ($example as $e) {
array_push($arr, $e);
}
}
Don't overcomplicate this, reassigning the first element to the parent array is quick and easy:
<?php
$array =
array (
0 =>
array (
'first' => 'Michael',
'last' => 'Thompson'
)
);
$array = $array[0];
var_export($array);
Output:
array (
'first' => 'Michael',
'last' => 'Thompson',
)
Or:
$array = array_shift($array);
Related
I am looking for a function to return an array and all its sub-structure for a specific criteria
Criteria:
php 5.6 compatible
Return the last instance of array with key name of !ENTITY with all
its values in-tact
Sample array:
For the multidimensional array, lets call that $arr, for this example structure it's 6 levels deep, we should not assume it's always 6 levels.
$arr = array("!ENTITY" =>
array("!ENTITY" =>
array("!ENTITY" =>
array("!ENTITY" =>
array("!ENTITY" =>
array("!ENTITY" =>
array("svg" =>
array(
0 => array("g" => "", "#id" => "Layer_2"),
1 => array("g" => "", "#id" => "Layer_3"),
),
"#version" => 1.2,
"#id" => "Layer_1",
),
"#different" => "layer"
),
"#all" => "layer"
),
"#here" => "layer"
),
"#goes" => "layer"
),
"#else" => "layer"
),
"#something" => "layer"
);
Expected Output:
I would like to return the final array for !ENTITY with it's sub-structure all in-tact. Here is a sample of the expected output:
Array
(
[svg] => Array
(
[0] => Array
(
[g] =>
[#id] => Layer_2
)
[1] => Array
(
[g]
[#id] => Layer_3
)
)
[#version] => 1.2
[#id] => Layer_1
)
You will need to recursively traverse the array and return resultant values if found like below:
<?php
function getLastValueForKey($data, $key){
$res = '';
foreach($data as $k => $value){
$sub_res = is_array($value) ? getLastValueForKey($value, $key) : '';
if($sub_res !== ''){
$res = $sub_res;
}else if($k === $key){
$res = $value;
}
}
return $res;
}
print_r(getLastValueForKey($arr, '!ENTITY'));
Online Demo
I'm trying to read a session variable, create arrays and concatenate them :
Session variable sample:
Array
(
[0] => Array
(
[idArticle] => 224
[ntypeArticle] => 1
)
[1] => Array
(
[idArticle] => 556
[ntypeArticle] => 2
)
[2] => Array
(
[idArticle] => 312
[ntypeArticle] => 1
)
)
I need to read this arrays one by one and create arrays by "ntypeArticle".
If ntypeArticle=1, create array1
If ntypeArticle=2, create array2
My code :
$type1 = array();
$type2= array();
$typeAll = array();
foreach($_SESSION['cart'] as $item)
{
if ($item['ntypeArticle'] == 1) {
$type1= array ( "Type" => '1', );
} else {
$type2= array ( "Type" => '2', );
}
array_push($typeAll , $type1 , $type2);
}
But this creates empty arrays.
Wanted output :
Array
(
[0] => Array
(
[type] => 1
)
[1] => Array
(
[type] => 2
)
[2] => Array
(
[type] => 1
)
)
All you need is this simple thing:
$out = [];
foreach($_SESSION['cart'] as $k => $item)
{
$out[$k] = ['Type' => $item['ntypeArticle']];
}
Now if you output $out variable you get what you need.
Try This
$newOp1 = array()
$newOp2 = array()
foreach($_SESSION['cart'] as $item){
if($item["ntypeArticle"] == 1){
$newOp1[]['type'] = $item["ntypeArticle"]
}else{
$newOp2[]['type'] = $item["ntypeArticle"]
}
}
print_r($newOp1);
print_r($newOp2);
Basing on information you provided, all you want to do is to extract nTypeArticle as type element. That's all.
//array from your example
$inputArray = array(
array(
'idArticle' => 224,
'nTypeArticle' => 1
),
array(
'idArticle' => 556,
'nTypeArticle' => 2
),
array(
'idArticle' => 312,
'nTypeArticle' => 1
),
);
$outputArray = array_map(function($inputElement) {
return array('type' => $inputElement['nTypeArticle']);
}, $inputArray);
var_dump($outputArray);
//Output (the same as yours):
//array (size=3)
// 0 =>
// array (size=1)
// 'type' => int 1
// 1 =>
// array (size=1)
// 'type' => int 2
// 2 =>
// array (size=1)
// 'type' => int 1
$output = new array();
$input = array(
array(
"idArticle" => 224,
"nTypeArticle" => 1
),
array(
"idArticle" => 556,
"nTypeArticle" => 2
),
array(
"idArticle" => 312,
"nTypeArticle" => 1
)
);
foreach($input as $article) {
array_push($output, new array("type"=>$article["nTypeArticle"]));
}
print_r($output);
This gives you the thing you asked for.
(Code has been not tested)
I am getting this array when form is submitted
array
'item' =>
array
0 => string 'Salt'
1 => string 'Pepper'
'quantity' =>
array (size=2)
0 => string '2 spoon'
1 => string '5'
and now want to rearrange above array, so it should look like
array
'0' =>
array
'item' => string 'Salt'
'quantity' => string '2 spoon'
'1' =>
array
'item' => string 'Pepper'
'quantity' => string '5'
I tried so many combinations but failed, will somebody help me how to rearrange this array. Any help will be more than appreciated.
Try this
$array = array(
'item' =>
array(
0 => 'Salt',
1 => 'Pepper'),
'quantity' =>
array(
0 => '2 spoon',
1 => '5')
);
$new_array = array();
foreach ($array['item'] as $key => $value) {
$new_array[$key]["item"] = $value;
$new_array[$key]["quantity"] = $array['quantity'][$key];
}
echo "<pre>";
var_dump($new_array);
Do it as below -
<?php
$arr=array(
'item' =>
array(
0 => 'Salt' ,
1 => 'Pepper'
),
'quantity' =>
array (
0 =>'spoon',
1 =>'5'
)
);
$result=array();
$com=array_combine($arr['item'],$arr['quantity']);
foreach($com as $k=>$v)
{
$result[]=array("item"=>$k,"quantity"=>$v);
}
print_r($result);
?>
OUTPUT
Array (
[0] => Array ( [item] => Salt [quantity] => spoon )
[1] => Array ( [item] => Pepper [quantity] => 5 )
)
try this, I think this would help you,
$a = array(
'item' =>
array(
0 => 'Salt',
1 => 'Pepper'),
'quantity' =>
array(
0 => '2 spoon',
1 => '5')
);
$i = 0;
foreach($a['item'] as $row){
$b[$i]["item"] = $row;
$b[$i]["quantity"] = $a['quantity'][$i];
$i++;
}
print_r($b);
Output from print_r() will be
Array
(
[0] => Array
(
[item] => Salt
[quantity] => 2 spoon
)
[1] => Array
(
[item] => Pepper
[quantity] => 5
)
)
You can simply use array_walk like as
$result = [];
array_walk($arr['item'], function($v, $k)use(&$result, $arr) {
$result[$k]['item'] = $arr['item'][$k];
$result[$k]['quantity'] = $arr['quantity'][$k];
});
print_r($result);
Demo
Hoping that your array is stored in the $array variable and that item is leading. Meaning that there is always an item in the array and not always a quantity
<?php
foreach($array['item'] as $key => $item) {
$newArray[$key]['item'] = $item;
if (isset($array['quantity'][$key]) {
$newArray[$key]['quantity'] = $array['quantity'][$key];
} else {
$newArray[$key]['quantity'] = 0;
}
?>
Right now, I have array sets like these:
[9] => Array
(
[sl] => 10
[upload_dt] => 2015-04-15 14:39:58
[total_files] => 3
[file_name] => logo01.png
[remarks] => qqq
[status] => pending
[download_file] => http://localhost/web/download_file21
)
[10] => Array
(
[sl] => 10
[upload_dt] => 2015-04-15 14:39:58
[total_files] => 3
[file_name] => face.jpg
[remarks] => 5645645
[status] => pending
[download_file] => http://localhost/web/download_file22
)
[11] => Array
(
[sl] => 10
[upload_dt] => 2015-04-15 14:39:58
[total_files] => 3
[file_name] => ID_11401871809904(15).pdf
[remarks] => 567567
[status] => pending
[download_file] => http://localhost/web/download_file23
)
Now, I need to merge same values in some of the indices into one arrays.
The merged array values should look like this in the end.
[9] => Array
(
[sl] => 10
[upload_dt] => 2015-04-15 14:39:58
[total_files] => 3
[file_name] => logo01.png , face.jpg, ID_11401871809904(15).pdf
[remarks] => qqq, 5645645 , 567567
[status] => pending, pending ,pending
[download_file] => http://localhost/web/download_file21,
http://localhost/web/download_file22,
http://localhost/web/download_file23
)
Now, I tried using array_merge but it didn't actually work in this case.
Solution will be like this:
<?php
$result = array();
$ar1[9] = Array
(
'sl' => 10,
'upload_dt' => '2015-04-15 14:39:58',
'total_files' => 3,
'file_name' => 'logo01.png',
'remarks' => 'qqq',
'status' => 'pending',
'download_file' => 'http://localhost/web/download_file21'
);
$ar1[10] = Array
(
'sl' => 10,
'upload_dt' => '2015-04-15 14:39:58',
'total_files' => 3,
'file_name' => 'face.jpg',
'remarks' => '5645645',
'status' => 'pending',
'download_file' => 'http://localhost/web/download_file22'
);
$ar1[11] = Array
(
'sl' => 10,
'upload_dt' => '2015-04-15 14:39:58',
'total_files' => 3,
'file_name' => 'ID_11401871809904(15).pdf',
'remarks' => 567567,
'status' => 'pending',
'download_file' => 'http://localhost/web/download_file23'
);
foreach($ar1 as $record){
$keys = array_keys($record);
foreach($keys as $key) {
if(array_key_exists($key,$result)){
$valeInKey = explode(',', $result[$key]);
if (!in_array($record[$key], $valeInKey)){
$result[$key]= $result[$key] .",".$record[$key];
}
} else{
$result[$key]= $record[$key];
}
}
}
echo"<pre>";print_r($result);exit;
?>
You're actually merging strings inside those arrays so just ditch the array_merge idea, and just use a simple loop then use the key as your basis to concatenate strings. Rough example:
$result = array();
foreach($array as $values) {
if(!isset($result[$values['sl']])) {
$result[$values['sl']] = $values; // initial
} else {
foreach(array('file_name', 'remarks', 'status', 'download_file') as $field) {
$result[$values['sl']][$field] .= ", {$values[$field]}";
}
}
}
Sample Output
array_merge won't work, because the keys would overwrite each other.
A solution would be to merge them with a the help of a foreach. Something like this:
$new = array();
foreach($arr as $key => $value) {
$new[$key] .= ", ".$value;
}
But you would have multiple entries for every single array you want to merge. If you just want to have them for a few, you have to check the key and do something accordingly.
I have two arrays:
Array
(
[0] => Array
(
[id] => 1
[type] => field
[remote_name] => Title
[my_name] => title
[default_value] => http%3A%2F%2Ftest.com
)
[1] => Array
(
[id] => 2
[type] => field
[remote_name] => BookType
[my_name] => book-type
[default_value] =>
)
[2] => Array
(
[id] => 3
[type] => value
[remote_name] => dvd-disc
[my_name] => dvd
[default_value] =>
)
)
Array
(
[title] => Test
[book-type] => dvd
)
I need to take each key in the second array, match it with the my_name value in the first array and replace it with the corresponding remote_name value of the first array while preserving the value of the second array.
There's got to be some carrayzy function to help!
EDIT: There will also be a few cases that the value of the second array will need to be replaced by the value of the first array's remote_name where the value of the second array matches the value of the first array's my_name. How can I achieve this?
EG: book-type => dvd should turn into BookType => dvd-disc
Like so?:
$first = array(
array(
'id' => 1,
'type' => 'field',
'remote_name' => 'Title',
'my_name' => 'title',
'default_value' => 'http%3A%2F%2Ftest.com',
),
array(
'id' => 2,
'type' => 'field',
'remote_name' => 'BookType',
'my_name' => 'book-type',
'default_value' => '',
),
array(
'id' => 3,
'type' => 'value',
'remote_name' => 'dvd-disc',
'my_name' => 'dvd',
'default_value' => '',
),
);
$second = array(
'title' => 'Test',
'book-type' => 'dvd',
);
$map = array('fields' => array(), 'values' => array());
foreach ($first as $entry) {
switch ($entry['type']) {
case 'field':
$map['fields'][$entry['my_name']] = $entry['remote_name'];
break;
case 'value':
$map['values'][$entry['my_name']] = $entry['remote_name'];
break;
}
}
$new = array();
foreach ($second as $key => $val) {
$new[isset($map['fields'][$key]) ? $map['fields'][$key] : $key] = isset($map['values'][$val]) ? $map['values'][$val] : $val;
}
print_r($new);
Output:
Array
(
[Title] => Test
[BookType] => dvd-disc
)
Explanation:
The first loop collects the my_name/remote_name pairs for fields and values and makes them more accessible.
Like so:
Array
(
[fields] => Array
(
[title] => Title
[book-type] => BookType
)
[values] => Array
(
[dvd] => dvd-disc
)
)
The second loop will traverse $second and use the key/value pairs therein to populate $new. But while doing so will check for key/value duplicates in $map.
Keys or values not found in the map will be used as is.
foreach($arr1 as &$el) {
$el['remote_name'] = $arr2[$el['my_name']];
}
unset($el);
I am not aware of such a carrayzy function, but I know how you could do it:
//$array1 is first array, $array2 is second array
foreach($array1 as $key => $value){
if (isset($value['remote_name'], $value['my_name']) && $value['remote_name'] && $value['my_name']){
$my_name = $value['my_name'];
if (isset($array2[$my_name])) {
$remote_name = $value['remote_name'];
$array2[$remote_name] = $array2[$my_name];
//cleanup
unset($array2[$my_name]);
}
}
}