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;
}
}
Related
I have an array as
$array = array (
0 => array( 'name' => 'zero'),
1 => array( 'name' => 'one'),
2 => array( 'name' => 'two'),
3 => array( 'name' => 'three'),
4 => array( 'name' => 'four'),
5 => array( 'name' => 'five'),
6 => array( 'name' => 'six'),
);
and I need to merge some elements according to a pattern
$pattern = array(
array('from'=>1, 'to'=>2, 'note'=>'something'),
array('from'=>3, 'to'=>5, 'note'=>'something'),
array('from'=>6, 'to'=>6, 'note'=>'something'),
);
How can I merge the elements to get an array of
$ result = array(
['0'] => array('name'=>'zero'),
['1,2'] => array('name'=>'one+two', 'note'=>'something'),
['3,4,5'] => array('name'=>'three+four+five', 'note'=>'something'),
['6'] => array('name'=>'six', 'note'=>'something'),
);
I understand that I should iterate one array in a loop and check the other one for the corresponding element to create a new array, but which one should I iterate?
If the array keys aren’t actually important, then I’d go about it like this:
$result = $processed = [];
foreach($pattern as $p) { // loop over the patterns
$temp = [];
for($i = $p['from']; $i <= $p['to']; ++$i) { // loop over from -> to
$temp[] = $array[$i]['name']; // collect names of those items
$processed[] = $i; // store index of item as an already processed one
}
$result[] = ['name' => implode('+', $temp), 'note' => $p['note']];
}
$temp = [];
foreach($array as $key => $item) {
if(!in_array($key, $processed)) { // if index is not in list of already processed items
$temp[] = $item['name'];
}
}
array_unshift($result, ['name' => implode('+', $temp)]); // add to front of result
That will get you a result of the form
Array
(
[0] => Array
(
[name] => zero
)
[1] => Array
(
[name] => one+two
[note] => something
)
[2] => Array
(
[name] => three+four+five
[note] => something
)
[3] => Array
(
[name] => six
[note] => something
)
)
I am having array within array values as below.
Array
(
[0] => Array
(
[0] => Array
(
[Floor] => Floor-1
)
[1] => Array
(
[Flat] => Flat A2
)
[2] => Array
(
[Area] => Balcony,
)
)
)
I need to make it as single associative array as below.
Array
(
[0] => Array
(
[Floor] => Floor-1
[Flat] => Flat A2
[Area] => Balcony,
)
)
How can i do this ?
This example should help you.
<?php
$arr = array(
array(
'floor'=>'Floor-1'
),
array(
'Flat'=>'Flat A2'
),
array(
'Area'=>'Balcony,'
),
);
$final_array = array();
foreach ($arr as $arr1) {
foreach ($arr1 as $key => $value) {
$final_array[$key] = $value;
}
}
?>
Output will be
Array
(
[floor] => Floor-1
[Flat] => Flat A2
[Area] => Balcony,
)
Here we have created an empty array called as $final_array we will append this array by using foreach loop.
Remember, if you have a same array key then the last value will overwrite like below.
<?php
$arr = array(
array(
'floor'=>'Floor-1',
'floor'=>'Floor-2',
),
array(
'Flat'=>'Flat A2'
),
array(
'Area'=>'Balcony,'
),
array(
'Area'=>'Balcony2,'
),
);
$final_array = array();
foreach ($arr as $arr1) {
foreach ($arr1 as $key => $value) {
$final_array[$key] = $value;
}
}
?>
Now, output will be
Array
(
[floor] => Floor-2
[Flat] => Flat A2
[Area] => Balcony2,
)
<?php
$array = [
[
[
'foo' => 'big'
],
[
'bar' => 'fat'
],
[
'baz' => 'mamma'
]
]
];
$merged[0] = array_reduce($array[0], function($carry, $item) {
return array_merge((array) $carry, $item);
});
var_export($merged);
Output:
array (
0 =>
array (
'foo' => 'big',
'bar' => 'fat',
'baz' => 'mamma',
),
)
This single line code is enough to do this
$newArr = call_user_func_array('array_merge',$dataArr); ///where $dataArr is your array..
call_user_func_array will call a callback function with array of parameters and array_merge will merge all these parameters in single array read more about call_user_func_array() and array_merge()
Example code:
<?php
$dataArr = array(
array(
'Floor'=>'Floor-1'
),
array(
'Flat'=>'Flat A2'
),
array(
'Area'=>'Balcony,'
),
);
$newArr = call_user_func_array('array_merge',$dataArr);
echo "<pre>"; print_r($newArr);
?>
This will give you :
Array
(
[Floor] => Floor-1
[Flat] => Flat A2
[Area] => Balcony,
)
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;
I array of arrays, what look something like that:
$messages = array (
0 =>
array(
'keyT' => 'id.key'
'mess' => array(
array(1,0)
)
...
)
I want to merge mess preperties of arrays where 'keyT' is not equals.
I run trought the arrays:
foreach ($messages as $k => $current) {
foreach ($messages as $ke => $all) {
if ($current['keyT'] == $all['keyT']) {
array_merge( ... )
}
}
}
But this not deve me any results. Maybe somebody can help me. Thanks!
Try this code
$messages = array(
0 =>
array(
'keyT' => 'A',
'mess' => array(
array(1, 0)
)
),
1 =>
array(
'keyT' => 'A',
'mess' => array(
array(1, 2)
)
),
2 =>
array(
'keyT' => 'B',
'mess' => array(
array(3, 4)
)
)
);
$result = array();
foreach ($messages as $msg) {
$key = $msg['keyT'];
if (!isset($result[$key])) {
$result[$key] = array();
}
$result[$key] = array_merge($result[$key], $msg['mess']);
}
print_r($result);
Output
Array
(
[A] => Array
(
[0] => Array
(
[0] => 1
[1] => 0
)
[1] => Array
(
[0] => 1
[1] => 2
)
)
[B] => Array
(
[0] => Array
(
[0] => 3
[1] => 4
)
)
)
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);