Concatenate array on loop php - php

I have this array
[0] => Array
(
[0] => My name
[1] => is
[2] => John
)
[1] => Array
(
[0] => My name is Jane
)
how to achieve this kind of output see below. If the array count is greater than one I want to combine them as one.
[0] => Array
(
[0] => My name is John
)
[1] => Array
(
[0] => My name is Jane
)
here is my code but it didn't work
foreach ($myArr as $key => $value) {
if (count($myArr[$key]) > 1) {
foreach ($value as $k => $v) {
$myArr[$key] .= $v;
}
}
}
thanks

Why not use implode?
$data = [['my name', 'is', 'John'],['my name is Jane']];
$results = [];
foreach ($data AS $id=>$datum)
if (count($datum) > 1)
$results[$id] = implode($datum, ' ');
else
$results[$id] = $datum[0];
results:
array(2) {
[0]=>
string(15) "my name is John"
[1]=>
string(15) "my name is Jane"
}

I suppose it would be like this:
foreach ($myArr as $key => $value) {
if (count($myArr[$key]) > 1) {
$myArr[$key][0] = '';
foreach ($value as $k => $v) {
$myArr[$key][0] .= $v;
}
array_splice($myArr[$key], 1, count($myArr[$key])-1);
}
}

I suppose it would be like this:
$ary[0] = Array("My name","is","John");
$ary[1] = Array( "My name is Jane" );
$i=0;
foreach ($ary as $ar_item) {
$merged="";
foreach ($ar_item as $ar_subitem)
{
$merged=$merged.$ar_subitem." ";
}
$ary[$i]=$merged;
$i++;
}
var_dump($ary);

Related

Merge two dimensional array in PHP

for a long time can't resolve smth looking like as very simple matter... I want merge a two dimensional arrays.
The example:
$arr1 = {
[532] =
{
[0] = "11"
[1] = "12"
}
[273] =
{
[0] = "99"
}
}
$arr2 = {
[532] =
{
[0] = "11"
[1] = "13"
}
}
And the result of merging should be, a map on common keys, exactly like that array:
$result = {
[532] =
{
[0] =
{
[0] = "11"
[1] = "12"
}
[1] =
{
[0] = "11"
[1] = "13"
}
}
[273]
[0] =
{
[0] = "99"
}
[1] =
{
}
}
I try sometihng like that:
$result = $arr1;
foreach ($arr2 as $key => $value) {
$result[$key] = isset($result[$key]) ? array_merge([$result[$key]], [$value]) : [$value];
}
But it doesnt work if $arr2 is empty :(
For the second array checking, you need to use isset() either array set or not:
Example:
<?php
$arr1 = array('532'=>array('11','12'),'273'=>array('99'));
$arr2 = array('532'=>array('11','13'));
$newArr = array();
foreach ($arr1 as $key => $value) {
if(isset($arr2[$key])){
$newArr[$key][] = $value;
$newArr[$key][] = $arr2[$key];
}
else{
$newArr[$key] = $value;
}
}
echo "<pre>";
print_r($newArr);
?>
Result:
Array
(
[532] => Array
(
[0] => Array
(
[0] => 11
[1] => 12
)
[1] => Array
(
[0] => 11
[1] => 13
)
)
[273] => Array
(
[0] => 99
)
)
Further more, if you want to merge both same index than you can use array_merge() some thing like that:
<?php
$arr1 = array('532'=>array('11','12'),'273'=>array('99'));
$arr2 = array('532'=>array('11','13'));
$newArr = array();
foreach ($arr1 as $key => $value) {
if(isset($arr2[$key])){
$newArr[$key][] = array_merge($value,$arr2[$key]);
}
else{
$newArr[$key] = $value;
}
}
echo "<pre>";
print_r($newArr);
?>
Result:
Array
(
[532] => Array
(
[0] => Array
(
[0] => 11
[1] => 12
[2] => 11
[3] => 13
)
)
[273] => Array
(
[0] => 99
)
)
Note that, ist script, will give you result as you need with unique index.
Second script will give you all values in one single array.
Probably something like this
$arr1 = {
[532] =
{
[0] = "11"
[1] = "12"
}
[273] =
{
[0] = "99"
}
}
$arr2 = {
[532] =
{
[0] = "11"
[1] = "13"
}
}
$newarray = array();
foreach ($arr1 as $key => $value) {
$cu = $arr1[$key];
$newarray[$key][] = $cu;
if(!isset($arr2[$key])) {
$newarray[$key][] = array();
}
else {
$newarray[$key][] = $arr2[$key];
}
}
foreach ($arr2 as $key => $value) {
if(!isset($newarray[$key])) {
$newarray[$key][] = $arr2[$key];
}
}

PHP replacing value in an array

I have this array with city codes:
$aryCityCodes = array ("LND", "NY");
And this other array with user data:
$ary = array (
array("John", "LND","London"),
array("Mary", "NY","New York"),
array("Larry", "AMS","Amsterdam")
);
I need to end up with an array like $ary but if the city code in $ary is contained in $aryCityCodes the name of the city in $ary has to be followed by "prime city"
So far, this is what I've done:
if($aryCityCodes)
{
if (count($ary) > 0)
{
foreach($ary as $item)
{
$bAux= false;
foreach ($item as $key => $value)
{
foreach ($aryCityCodes as $aCityCode)
{
if ($aCityCode == $value)
{
$bAux = true;
}
if($bAux)
{
$value = $value.' prime city';
}
}
}
}
}
}
But this does not work, it does not change the name of the city
What am I doing wrong?
Thanks!
I think I see what you need:
if($aryCityCodes) {
if (count($ary) > 0) {
foreach ($ary as $key => $row) {
if (in_array($row[1], $aryCityCodes)) {
$ary[$key][2] .= ' prime city';
}
}
}
}
Demo : https://eval.in/599514
Check output :
Array
(
[0] => Array
(
[0] => John
[1] => LND
[2] => London prime city
)
[1] => Array
(
[0] => Mary
[1] => NY
[2] => New York prime city
)
[2] => Array
(
[0] => Larry
[1] => AMS
[2] => Amsterdam
)
foreach is working on a copy of your data, if you dont explicitly specify it should be "by reference".
Change both foreaches like so:
foreach($ary as &$item)
And
foreach ($item as $key => &$value)
Create new array, look in the arrCityCodes array for match (where you can also add strict matching) and append the value if a match is found.
$newArray =[];
foreach ($ary as $row) {
if (in_array($row[1], $arrCityCodes)) {
$newArray[] = [
$row[0], $row[1], $row[2] . ' prime city'
];
} else {
$newArray[] = [
$row[0], $row[1], $row[2]
];
}
}
The benefit here is that you still have access to the original object which can be handy sometimes.

Insert multidimensional array into csv in PHP

I have an array which is structured like this
[cars] => Array
(
[0] => 43063
[1] => 17306
[2] => 116078
)
[houses] => Array
(
[0] => 13300
[1] => 32243
)
[garage] => Array
(
[0] => 13094
[1] => 30649
)
[hotels] => Array
(
[0] => 10025
[1] => 59468
[2] => 29734
)
I would like to create a csv file out of that array. My csv file should be structured this way
cars,43063,17306,116078
houses,13300,32243,1000
garage,13094,30649,1000
hotels,10025,59468,29734
I have tried several codes, but i am not getting what i want, how can i acheive it in php ?
Here is the var dump of my array
array(4) {
["23"]=>
array(1) {
["cars"]=>
int(43063)
}
[23]=>
array(4) {
["cars"]=>
int(17306)
["houses"]=>
int(13300)
["garage"]=>
int(13094)
["hotels"]=>
int(10025)
}
[22]=>
array(4) {
["cars"]=>
int(116078)
["houses"]=>
int(32243)
["garage"]=>
int(30649)
["hotels"]=>
int(59468)
}
[21]=>
array(1) {
["hotels"]=>
int(29734)
}
}
I would like to have a csv that contains 4 lines, one line for each key (hotels,car,garage,etc..
cars,43063,17306,116078
houses,13300,32243,1000
garage,13094,30649,1000
hotels,10025,59468,29734
You could try something like this
function arrayToValues(array $data)
{
$output = array();
foreach ($data as $key => $item) {
if (is_array($item)) {
$output = array_merge($output, array($key), arrayToValues($item));
} else {
$output[] = $item;
}
}
return $output;
}
$csvData = implode(',', arrayToValues($yourArrayData));
If you want to write the output you could use fputcsv in combination with the function instead.
Quick and dirty:
foreach ($arr as $key => $vals) {
echo $key . implode(",", $vals) . "\n";
}
UPDATE:
$transformed = array();
foreach ($arr as $item) {
foreach ($item as $key => $val) {
$transformed[$key][] = $val;
}
}
foreach ($transformed as $key => $vals) {
echo $key . implode(",", $vals) . "\n";
}

Manipulate array foreach

I have array 1 and it should be 2
Does anyone have an idea / solution?
Do i need foreach or for loop?
1.
Array
(
[0] => Array
(
[category_id] => 5
[category] => Pages
)
)
Must be:
Array
(
[0] => Array
(
[5] => Pages
)
)
I have this but this doent work...
for($x = 0; $x <= $counter; $x++){
foreach ($Categories[$x] as $key => $value){
echo $key.' '. $value.'<br>';
}
$test[$x]['category_id'] .= $Categories[$x]['category'];
}
Thanks for all the help!
Code:
<?php
$arr = array(
array(
'category_id' => 5 ,
'category' => 'Pages',
),
);
$new = array();
foreach ($arr as $item) {
$new[] = array(
$item['category_id'] => $item['category']
);
}
print_r($new);
Result:
Array
(
[0] => Array
(
[5] => Pages
)
)
$output=array();
foreach($array as $k=>$v)
{
$output[$v['category_id']]=$v['category'];
}
echo "<pre />";
print_r($output);
Demo1
Demo 2
for multidimensinal result :
$output=array();
foreach($array as $k=>$v)
{
$output[][$v['category_id']]=$v['category'];
}
echo "<pre />";
print_r($output);
As you said you will need a foreach loop to manupulate you array.
Example
$array = array
(
'0' => array
(
'category_id' => '5',
'category' => 'Pages'
)
);
$new_array = array();
foreach($array as $val)
{
$new_array[$val['category_id']] = $val['category'];
}
var_dump($new_array);
this will output
array(1) { [5]=> string(5) "Pages" }

PHP group repeated elements in array

How can the array be separated into groups of identical elements (concatenated chars).
For example, I have this array:
Array(
[0] => 1
[1] => 1
[2] => 1
[3] => 2
[4] => 2
[5] => 1
)
and want to group all identical numbers in only one element, bringing the together with concatenation to get something like this:
Array(
[0] => 111
[1] => 22
[2] => 1
)
To group all identical elements by concatenating them together (will not work for concatenating just the neighboring identical elements)
$arr = array (1,1,1,2,2,1);
$sum = array_count_values($arr);
array_walk($sum, function(&$count, $value) {
$count = str_repeat($value, $count);
});
print_r($sum);
Output
Array (
[1] => 1111
[2] => 22 )
Or for concatenating just the neighboring identical elements
$prev=null;
$key=0;
foreach ( $arr as $value ) {
if ($prev == $value){
$res[$key] .= $value;
} else {
$key++;
$res[$key] = $value;
$prev=$value;
}
}
print_r($res);
Output
Array (
[1] => 111
[2] => 22
[3] => 1 )
Here two functions
1 will return
Array
(
[1] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
)
[2] => Array
(
[0] => 2
[1] => 2
)
)
as output and second one will return
Array
(
[1] => 1111
[2] => 22
)
as output
$array = array(
1,1,1,2,2,1
);
print_r(groupArray($array));
print_r(groupSame($array));
function groupArray($array){
$temp = array();
foreach($array as $value){
if(!isset($temp[$value])){
$temp[$value] = array();
}
array_push($temp[$value],$value);
}
return $temp;
}
function groupSame($array){
$temp = array();
foreach($array as $value){
if(!isset($temp[$value])){
$temp[$value] = "";
}
$temp[$value] .= $value;
}
return $temp;
}
<?php
$i=0;
foreach($Arrays as $key=>$val) {
if (!isset($array[$i]))
$array[$i]=$val;
else if (!isset($mem) || $val==$mem)
$array[$i]=10*$array[$i]+$mem;
else
$i++;
$mem=$val;
}
?>
$array = array(1,1,1,2,2,1);
$start = "";
$new_array = array();
foreach($array as $v){
$v = (string)$v;
if($start==$v){
$count = count($new_array) - 1;
$val = $new_array[$count].$v;
$new_array[$count] = $val;
} else{
$new_array[] = $v;
}
$start = $v;
}
var_dump($new_array);
Tested and its working..
Output > array(3) { [0]=> string(3) "111" [1]=> string(2) "22" [2]=> string(1) "1" }
$newarray = array_unique($oldarray);
$count = array_count_values($oldarray);
foreach($newarray as &$val){
$val = str_repeat($val,$count[$val]);
}
http://codepad.org/FUf0n8sz

Categories