Convert array to another character [php] - php

I have data in the form:
$data = Array ( [0] => 1 [1] => 4 [2] => 3 [3] => 3 )
I want to convert it to:
$x = [[1], [2], [3], [4]];
I do not know how to do this?
I'm using the library PHP-ML ( http://php-ml.readthedocs.io/en/latest/machine-learning/regression/least-squares/ ).

If you want to create array from values, you can do it this way:
$x = [];
foreach($data as $key => $value) {
array_push($x, $value);
}
If you want to create array of arrays from values you can edit it like this:
$x = [];
foreach($data as $key => $value) {
array_push($x, [$value]);
}

$data = array(1,4,3,3);
$x = '[['.implode('], [', $data).']]';
echo $x;

$data = array(0 => "0", 1 => "1", 2 => "2", 3 => "3");
$output;
$halt = count($data) - 1;
for($i = 0; $i < count($data); $i++){
if($i==$halt){
$output.="[".$data[$i]."]";
}else{
$output.="[".$data[$i]."]".", ";
}
}
$x = "[".$output."]";
echo $x;
Like so?
But why change array to array?
Ahhh I see, You want it in a json format?*
$array = array( 0 => [1], 1 => [2] , 2 => [3], 3 => [3] );
$x = json_encode($array, JSON_HEX_APOS);
echo $x;
[[1],[2],[3],[3]]

Related

How to concatenate an array with a 'foreach' loop?

I have several arrays.
example:
$a = Array(
[0] => #ID_1
[1] => #ID_2
[2] => #ID_3
)
$b = Array(
[0] => ABC
[1] => cde
[2] => fgh
)
$c = Array(
[0] => 000
[1] => 111
[2] => 222
)
How to concatenate these data fields using any foreach, for, while loop?
Expected result:
$result = '#ID_1 ABC 000';
I try something like this:
$result = '';
foreach($a as $aa) {
$result .= $aa ." ";
foreach ($b as $bb) {
$result .= $bb ." ";
foreach($c as $cc) {
$result .= $cc .'<br>';
}
}
}
but the result did not meet expectations.
Can anyone advise how to use foreach to chain these arrays together? Thank you. Thank you very much.
If you need foreach loop then use next code:
$res = [];
foreach($a as $ind=>$val){
$res[$ind] = $val." ".$b[$ind]." ".$c[$ind];
}
Demo
You can do something like this.
$arr1 = ["#ID_1", "#ID_2", "#ID_3"];
$arr2 = ["ABC", "DEF", "FGH"];
$arr3 = ["000", "111", "222"];
$arrayLength = count($arr1);
$i = 0;
$result = [];
while ($i < $arrayLength)
{
$result[] = $arr1[$i]." ".$arr2[$i]." ".$arr3[$i];
$i++;
}
foreach($result as $item){
echo $item."<br/>";
}
According to what you're asking, you want to join elements with the key 0 from all arrays, then with the key 1 and so on, so instead of doing a foreach loop you could use a for loop using the key:
<?php
$a = Array(
0 => "#ID_1",
1 => "#ID_2",
2 => "#ID_3",
);
$b = Array(
0 => "ABC",
1 => "cde",
2 => "fgh"
);
$c = Array(
0 => 000,
1 => 111,
2 => 222
);
$length = sizeof($a);
$output = '';
for($i = 0; $i<$length; $i++) {
$output .= $a[$i] . ' / ' . $b[$i] . ' / ' . $c[$i] . '<br>';
}
echo $output;
?>
Outputs:
#ID_1 / ABC / 0
#ID_2 / cde / 111
#ID_3 / fgh / 222
Way to do this using foreach, if number of elements in each array is same.
$arr1 = ["#ID_1", "#ID_2", "#ID_3"];
$arr2 = ["ABC", "DEF", "FGH"];
$arr3 = ["000", "111", "222"];
foreach($arr1 as $k => $item) {
echo "$item {$arr2[$k]} {$arr3[$k]}<br>";
}
using for loop this way would give you your expected result
<?php
$a = Array(
0 => '#ID_1',
1 => '#ID_2',
2 => '#ID_3'
);
$b = Array(
0 => 'ABC',
1 => 'cde',
2 => 'fgh'
);
$c = Array(
0 => '000',
1 => '111',
2 => '222'
);
$arrlengtha = count($a);
$arrla = $arrlengtha - 2;
$arrlengthb = count($b);
$arrlb = $arrlengthb - 2;
$arrlengthc = count($c);
$arrlc = $arrlengthc - 2;
for($x = 0; $x < $arrla; $x++) {
echo $a[$x]." ";
}
for($x = 0; $x < $arrlb; $x++) {
echo $b[$x]." ";
}
for($x = 0; $x < $arrlc; $x++) {
echo $c[$x]." ";
}
?>

How to merge two array in mysql query

From MySQL join query I got result like:
Array ( [0] => c1 [1] => ot1 [2] => ot1 [3] => R )
Array ( [0] => 20 [1] => 10 [2] => 15 [3] => 5 )
But I want result like:
c1 = [20]
ot1 = [10,15]
R = [5]
Please help me.
Assuming
$array1 = array( 0 => 'c1', 1 => 'ot1', 2 => 'ot1' 3 => 'R' )
$array2 = array( 0 => 20, 1 => 10, 2 => 15, 3 => 5 )
Try this:
for($i = 0; $i < count($array1); $i++){
if(!isset(${$array1[$i]}))
${$array1[$i]} = [];
${$array1[$i]}[] = $array2[$i];
}
Note that this works only when keys are continous integers starting from 0 and both arrays have the same dimension
Assuming the first array is called $array1 and the other is called $array2 try this:
$merged = []; //new array for merged values
foreach ($array1 as $key => $value) { //iterate over the array which holds keys
if (!isset($merged[$value])) { //if a key does not exist in new array yet
$merged[$value] = []; //add it
}
$merged[$value][] = $array2[$key]; //add new value from the other array under this key
}
as long as the integrity of your arrays is preserved, there are no restrictions about continuous keys like in the other answer
Use this one
$array1 = array('c1', 'ot1', 'ot1', 'R');
$array2 = array(20, 10, 15, 5);
$array3 = array();
for ($i = 0; $i < count($array1); $i++) {
if (array_key_exists($array1[$i], $array3)) {
$array3[$array1[$i]] = array($array3[$array1[$i]], $array2[$i]);
} else {
$array3[$array1[$i]] = $array2[$i];
}
}

How to split the string in two arrays in Php

I have one array like this :
$array='{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1},{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}'
I want first split to two array like this :
$array[0]={b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1}
And
$array[1]={b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}
I change every array with this code
foreach ($b as $k => $m) {
if ($k % 2 == 0) {
$even[]= $m;
}
else {
$odd[] = $m;
}
}
$ff=array_combine($even,$odd);
I want output change like this
Array( Array[0] => ([b_price] => 9500 [b_discount] => 10 [mainPrice] => 95000 [total] => 95000 [title] =>obj1)
Array[1] => ([b_price] => 1500 [b_discount] => 15 [mainPrice] => 15000 [total] => 22500 [title] => obj2))
Two approaches:
-- using explode and array_map functions:
$str = '{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1},{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}';
$result = array_map(function($v){
$r = [];
$arr = explode(',', trim($v, '{}'));
foreach ($arr as $k => $v) {
if (!($k % 2)) $r[$v] = $arr[$k+1];
}
return $r;
}, explode('},{', $str));
print_r($result);
-- using additional preg_match_all and array_combine functions:
$str = '{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1},{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}';
$result = array_map(function($v){
preg_match_all('/([^,]+),([^,]+),?/', trim($v, '{}'), $m);
return array_combine($m[1], $m[2]);
}, explode('},{', $str));
print_r($result);
The output:
Array
(
[0] => Array
(
[b_price] => 9500
[b_discount] => 10
[mainPrice] => 95000
[total] => 95000
[title] => obj1
)
[1] => Array
(
[b_price] => 1500
[b_discount] => 15
[mainPrice] => 15000
[total] => 22500
[title] => obj2
)
)
you should change your needle, in your array string,
i have changed it with semicolon,
$arrayString='{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1};{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}';
echo $arrayString;
echo "<pre>"; print_r (explode(";",$arrayString));
$b=explode(";",$arrayString);
foreach ($b as $k => $m) {
if ($k % 2 == 0) {
$even[]= $m;
}
else {
$odd[] = $m;
}
}
$ff=array_combine($even,$odd);
So, I write this decision. Maybe it can be more clear, but it works.
$array='{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1},{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}';
/*Making array from string*/
$tmp_array = explode("},{", $array);
/*Removing { symbols*/
$tmp_array[0] = substr($tmp_array[0],1);
$tmp_array[1] = substr($tmp_array[1],0,-1);
/*Making arrays from string [0] and [1]*/
$tmp_array[0] = explode(',',$tmp_array[0]);
$tmp_array[1] = explode(',',$tmp_array[1]);
$new_array = [];
/*Creating associative arrays*/
for($a = 0; $a < count($tmp_array); $a++) {
$new_as_array = [];
for($i = 0; $i <= count($tmp_array[0]); $i+=2) {
if($i + 1 <= count($tmp_array[0])) {
$new_as_array[$tmp_array[$a][$i]] = $tmp_array[$a][$i + 1];
}
}
$new_array[] = $new_as_array;
}
print_r($new_array);

combine arrays and concat value?

Little complex to explain , so here is simple concrete exemple :
array 1 :
Array
(
[4] => bim
[5] => pow
[6] => foo
)
array 2 :
Array
(
[n] => Array
(
[0] => 1
)
[m] => Array
(
[0] => 1
[1] => 2
)
[l] => Array
(
[0] => 1
[1] => 4
[2] => 64
)
And i need to output an array 3 ,
array expected :
Array
(
[bim] => n-1
[pow] => Array
(
[0] => m-1
[1] => m-2
)
[foo] => Array
(
[0] => l-1
[1] => l-4
[2] => l-64
)
Final echoing OUTPUT expected:
bim n-1 , pow m-1 m-2 ,foo l-1 l-4 l-64 ,
I tried this but seems pity:
foreach($array2 as $k1 =>$v1){
foreach($array2[$k1] as $k => $v){
$k[] = $k1.'_'.$v);
}
foreach($array1 as $res =>$val){
$val = $array2;
}
Thanks for helps,
Jess
CHALLENGE ACCEPTED
<?php
$a = array(
4 => 'bim',
5 => 'pow',
6 => 'foo',
);
$b = array(
'n' => array(1),
'm' => array(1, 2),
'l' => array(1, 4, 64),
);
$len = count($a);
$result = array();
$aVals = array_values($a);
$bKeys = array_keys($b);
$bVals = array_values($b);
for ($i = 0; $i < $len; $i++) {
$combined = array();
$key = $aVals[$i];
$prefix = $bKeys[$i];
$items = $bVals[$i];
foreach ($items as $item) {
$combined[] = sprintf('%s-%d', $prefix, $item);
};
if (count($combined) === 1) {
$combined = $combined[0];
}
$result[$key] = $combined;
}
var_dump($result);
?>
Your code may be very easy. For example, assuming arrays:
$one = Array
(
4 => 'bim',
5 => 'pow',
6 => 'foo'
);
$two = Array
(
'n' => Array
(
0 => 1
),
'm' => Array
(
0 => 1,
1 => 2
),
'l' => Array
(
0 => 1,
1 => 4,
2 => 64
)
);
You may get your result with:
$result = [];
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$result[$oneValue] = array_map(function($item) use ($twoKey)
{
return $twoKey.'-'.$item;
}, $twoValue);
};
-check this demo Note, that code above will not make single-element array as single element. If that is needed, just add:
$result = array_map(function($item)
{
return count($item)>1?$item:array_shift($item);
}, $result);
Version of this solution for PHP4>=4.3, PHP5>=5.0 you can find here
Update: if you need only string, then use this (cross-version):
$result = array();
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$temp = array();
foreach($twoValue as $item)
{
$temp[] = $twoKey.'-'.$item;
}
$result[] = $oneValue.' '.join(' ', $temp);
};
$result = join(' ', $result);
As a solution to your problem please try executing following code snippet
<?php
$a=array(4=>'bim',5=>'pow',6=>'foo');
$b=array('n'=>array(1),'m'=>array(1,2),'l'=>array(1,4,64));
$keys=array_values($a);
$values=array();
foreach($b as $key=>$value)
{
if(is_array($value) && !empty($value))
{
foreach($value as $k=>$val)
{
if($key=='n')
{
$values[$key]=$key.'-'.$val;
}
else
{
$values[$key][]=$key.'-'.$val;
}
}
}
}
$result=array_combine($keys,$values);
echo '<pre>';
print_r($result);
?>
The logic behind should be clear by reading the code comments.
Here's a demo # PHPFiddle.
//omitted array declarations
$output = array();
//variables to shorten things in the loop
$val1 = array_values($array1);
$keys2 = array_keys($array2);
$vals2 = array_values($array2);
//iterating over each element of the first array
for($i = 0; $i < count($array1); $i++) {
//if the second array has multiple values at the same index
//as the first array things will be handled differently
if(count($vals2[$i]) > 1) {
$tempArr = array();
//iterating over each element of the second array
//at the specified index
foreach($vals2[$i] as $val) {
//we push each element into the temporary array
//(in the form of "keyOfArray2-value"
array_push($tempArr, $keys2[$i] . "-" . $val);
}
//finally assign it to our output array
$output[$val1[$i]] = $tempArr;
} else {
//when there is only one sub-element in array2
//we can assign the output directly, as you don't want an array in this case
$output[$val1[$i]] = $keys2[$i] . "-" . $vals2[$i][0];
}
}
var_dump($output);
Output:
Array (
["bim"]=> "n-1"
["pow"]=> Array (
[0]=> "m-1"
[1]=> "m-2"
)
["foo"]=> Array (
[0]=> "l-1"
[1]=> "l-4"
[2]=> "l-64"
)
)
Concerning your final output you may do something like
$final = "";
//$output can be obtained by any method of the other answers,
//not just with the method i posted above
foreach($output as $key=>$value) {
$final .= $key . " ";
if(count($value) > 1) {
$final .= implode($value, " ") .", ";
} else {
$final .= $value . ", ";
}
}
$final = rtrim($final, ", ");
This will echo bim n-1, pow m-1 m-2, foo l-1 l-4 l-64.

How to convert an array into key-value pair array?

I am having this array :
array(
0 => array("name", "address", "city"),
1=> array( "anoop", "palasis", "Indore"),
2=> array( "ravinder", "annapurna", "Indore")
)
and i want to make this array in this way :
array(
0 => array("name" = >"anoop" , "address" = >"palasia", "city" = >"Indore"),
1 => array("name" = >"ravinder" , "address" = >"annapurna", "city" = >"Indore")
)
The modern way is:
$data = array_column($data, 'value', 'key');
In your case:
$data = array_column($data, 1, 0);
Use array_combine. If $array contains your data
$result = array(
array_combine($array[0], $array[1]),
array_combine($array[0], $array[2])
);
In general
$result = array();
$len = count($array);
for($i=1;$i<$len; $i++){
$result[] = array_combine($array[0], $array[$i]);
}
If your data are in $array:
$res = array();
foreach ($array as $key=>$value) {
if ($key == 0) {
continue;
}
for ($i = 0; $i < count($array[0]); $i++) {
$res[$array[0][$i]] = $value[$i];
}
}
The result is now in $res.
Here is a function that you can use:
function rewrap(Array $input){
$key_names = array_shift($input);
$output = Array();
foreach($input as $index => $inner_array){
$output[] = array_combine($key_names,$inner_array);
}
return $output;
}
Here is a demonstration:
// Include the function from above here
$start = array(
0 => array("name", "address", "city"),
1 => array("anoop", "palasis", "Indore"),
2 => array("ravinder", "annapurna", "Indore")
);
print_r(rewrap($start));
This outputs:
Array
(
[0] => Array
(
[name] => anoop
[address] => palasis
[city] => Indore
)
[1] => Array
(
[name] => ravinder
[address] => annapurna
[city] => Indore
)
)
Note: Your first array defined index 1 twice, so I changed the second one to 2, like this:
array(0 => array("name", "address", "city"), 1 => array("anoop", "palasis", "Indore"),2 => array("ravinder", "annapurna", "Indore"))
That was probably just a typo.
Assuming that you are parsing a CSV file, check out the answers to this question:
Get associative array from csv

Categories