PHP Imploding Multidimensional Array - php

I need to implode an multi-dimensional array in a string using implode, i tried using the array_map shown here: stackoverflow.com but i failed.
Array:
Array (
[0] => Array (
[code] => IRBK1179
[qty] => 1
)
[1] => Array (
[code] => IRBK1178
[qty] => 1
)
[2] => Array (
[code] => IRBK1177
[qty] => 1
)
)
Desired Output:
IRBK1179:1|IRBK1178:1|IRBK1177:1

Use foreach and implode() inner array with : and then implode() new array with |. Try below code.
$arr = Array (
0 => Array ( 'code' => 'IRBK1179','qty' => 1 ),
1 => Array ( 'code' => 'IRBK1178','qty' => 1 ),
2 => Array ( 'code' => 'IRBK1177','qty' => 1 ) );
$newArr = array();
foreach ($arr as $row)
{
$newArr[]= implode(":", $row);
}
echo $finalString = implode("|", $newArr);
Output
IRBK1179:1|IRBK1178:1|IRBK1177:1
Working Online Demo: Click Here
Use explode() to get back array from string.
Try below code.
$finalString = "IRBK1179:1|IRBK1178:1|IRBK1177:1";
$firstArray = explode("|", $finalString);
foreach($firstArray as $key=>$row)
{
$tempArray = explode(":", $row);
$newArray[$key]['code'] = $tempArray[0];
$newArray[$key]['qty'] = $tempArray[1];
}
print_r($newArray);
Output
Array
(
[0] => Array
(
[code] => IRBK1179
[qty] => 1
)
[1] => Array
(
[code] => IRBK1178
[qty] => 2
)
[2] => Array
(
[code] => IRBK1177
[qty] => 1
)
)
Working Demo : Click Here

As i commented out, use the implode and foreach. for inner array use : and for outer array use |.
$str = array();
foreach($arr as $val){
$str[] = implode(":", $val);
}
echo implode("|", $str); //IRBK1179:1|IRBK1178:1|IRBK1177:1

Both other answers given by Frayne and Ruchish are correct.
Here is another alternative using array_map.
$arr = [[ 'code' => 'IRBK1179','qty' => 1 ],
[ 'code' => 'IRBK1178','qty' => 1 ],
[ 'code' => 'IRBK1177','qty' => 1 ]];
echo implode('|', array_map(function ($val) {
return $val['code'].':'.$val['qty'];
}, $arr));
Output:-
IRBK1179:1|IRBK1178:1|IRBK1177:1

Simple solution using array_reduce function:
// $arr is the initial array
$result = array_reduce($arr, function($a, $b){
$next = $b['code'].":".$b['qty'];
return (!$a)? $next : (((is_array($a))? $a['code'].":".$a['qty'] : $a)."|".$next);
});
print_r($result);
The output:
IRBK1179:1|IRBK1178:1|IRBK1177:1

Here is my version:
<?php
$arr = [
0 => ['code' => 'IRBK1179', 'qty' => 1],
1 => ['code' => 'IRBK1178', 'qty' => 1],
2 => ['code' => 'IRBK1177', 'qty' => 1],
];
$str = implode("|", array_map(function ($value) {return implode(":", array_values($value));}, array_values($arr)));
var_dump($str); # "IRBK1179:1|IRBK1178:1|IRBK1177:1"

$array = array (
'0' => array (
'code' => 'IRBK1179',
'qty' => '1'
),
'1' => array (
'code' => 'IRBK1178',
'qty' => '1'
),
'2' => array (
'code' => 'IRBK1177',
'qty' => '1'
)
);
$string ='';
foreach($array as $key=>$value){
$string .= $value['code'].':'.$value['qty'].'|';
}
echo $string;

Related

how to explode array in php

i have data array, and this my array
Array
(
[0] => Array
(
[id] => 9,5
[item] => Item A, Item B
)
[1] => Array
(
[id] => 3
[item] => Item C
)
)
in array 0 there are two ID which I separated using a comma, I want to extract the data into a new array, how to solve this?
so the output is like this
Array
(
[0] => Array
(
[id] => 9
[item] => Item A
)
[1] => Array
(
[id] => 3
[item] => Item C
)
[2] => Array //new array
(
[id] => 5
[item] => Item B
)
)
this my code
$arr=array();
foreach($myarray as $val){
$arr[] = array(
'id' => $val['id'],
'item' => $val['item'],
);
}
echo '<pre>', print_r($arr);
$arr = [
array(
'id' => '9,5',
'item' => 'Item A, Item B'
),
array(
'id' => 3,
'item' => 'Item C'
)
];
$newArr = array_reduce($arr, function($tmp, $ele){
$arrIds = explode(',', $ele['id']);
$arrItems = explode(',', $ele['item']);
forEach($arrIds as $key => $arrId) {
$tmp[] = array('id' => $arrId, 'item' => $arrItems[$key]);
}
return $tmp;
});
The code down below should do the job. But I didn't understand why you didn't create those items seperately in the first place.
foreach ($arr as $i => $data) {
if (!str_contains($data['id'], ',')) continue;
$items = explode(',', $data['item']);
foreach(explode(',', $data['id']) as $i => $id) {
$new = ['id' => $ids[$i], 'item' => $items[$i]];
if ($i) $arr[] = $new;
else $arr[$i] = $new;
}
}

Array Push Inside an array

I want to push another array inside array.
This is my array. I want to push another array on textTabs .
Array
(
[recipients] => Array
(
[signers] => Array
(
[0] => Array
(
[email] => rm#gmail.com
[tabs] => Array
(
[checkboxTabs] => Array
(
[0] => Array
(
[tabLabel] => sampleCheckbox
)
)
[textTabs] => Array
(
[0] => Array
(
[tabLabel] => CompanyName
[value] => Qwerty
)
[1] => Array
(
[tabLabel] => TradingName
[value] => Qwerty
)
[2] => Array
(
[tabLabel] => ContactName
[value] => RM
)
)
)
)
)
)
)
This is my array that i want to add:
$array2 = array(
"tabLabel"=>"MonthlyTotal",
"value"=>$monthlytotal
);
And this is my php code:
$data = array_push($array1['recipients']['signers']['0']['tabs']['textTabs'], $array2);
But I was not able to push it. Thank you for your help.
No need of assignment of array_push() to $data,as child-array pushed to initial array itself. Just do:
array_push($array1['recipients']['signers']['0']['tabs']['textTabs'], $array2);
print_r($array1);
Output:- https://3v4l.org/sntUP
I always prefer doing assignment like below:
$array1['recipients']['signers']['0']['tabs']['textTabs'][] = $array2;
Output:-https://3v4l.org/nHHUB
If you do love a portable way to do add an array or any other values to any key, you may do it using recursive function. Let's see an example below:
<?php
$old_array = [
'one' => 'value for one',
'two' => 'value for two',
'three' => [
'four' => 'value for four',
'five' => 'value for five',
'six' => [
'seven' => 'value for seven',
'eight' => 'value for eight',
],
],
];
function addArrayToKey($array, $callback){
$result = [];
foreach($array as $key => $value){
if(is_array($value)) {
$result[$key] = addArrayToKey($value, $callback);
} else {
$result[$key] = $callback($key, $value);
}
}
return $result;
}
function callback($key, $value) {
if('seven' == $key) {
return ['one', 'two', 'three' => ['four', 'five']];
}
return $value;
}
echo '<pre>';
print_r(addArrayToKey($old_array, 'callback'));

shift multidimentional array to single array

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

Rearrange array

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;
}
?>

array transformation in php

how would you turn this array:
Array
(
[0] => 234234234
[1] => 657567567
[2] => 234234234
[3] => 5674332
)
into this:
Array
(
[contacts] => Array(
[0] => Array
(
[number] => 234234234
[contact_status] => 2
[user_id] =>3
)
[1] => Array
(
[number] => 657567567
[contact_status] => 2
[user_id] =>3
)
[3] => Array
(
[number] => 234234234
[contact_status] => 2
[user_id] =>3
)
[4] => Array
(
[number] => 5674332
[contact_status] => 2
[user_id] =>3
)
)
)
is there a cakephp specific way how to transform this array?
thank you
nicer
$contact_status = 2;
$user_id = 1;
foreach($input as $number)
$output['contacts'][] = compact('number', 'contact_status', 'user_id');
Try this:
$output = array('contacts'=>array());
foreach ($input as $val) {
$output['contacts'][] = array(
'number' => $val,
'contact_status' => 2,
'user_id' => 3
);
}
I assume that contact_status and user_id are static since you didn’t tell anything else.
$input = array(...);
$arr = array();
foreach ($input as $id) {
$arr[] = array(
'number' => $id,
'contact_status' => 2,
'userid' => 3;
);
}
$output = array('contacts' => $arr);
A little bit of cleanup from sterofrog's solution. Declare the array and use array_push instead of assigning it to an empty index.
$output = array( );
$contact_stats = 2;
$user_id = 3;
foreach( $input as $number ) {
array_push( $output[ 'contact' ], compact(
'number',
'contact_status',
'user_id'
));
}
You can simply use the array_map function like this:
$result = array_map(function ($n){
return array(
'number' => $n,
'contact_status' => 2,
'user_id' => 3);
}, $original);

Categories