Arrays with keys to custom string php [duplicate] - php

This question already has answers here:
How to implode array with key and value without foreach in PHP
(13 answers)
Closed 8 months ago.
I have this array
Array ( [13] => 500 [16] => 1000 )
Array ( [12] => 1 [13] => 1111 )
how can I make them a string as this shape
13 500, 16 1000
12 1, 13 1111

Using implode and array_map
$input = [13 => 500, 16 => 1000];
$output = implode(', ', array_map(
function ($v, $k) {
return $k . " " . $v;
}, $input, array_keys($input))
);
var_dump($output);
Using foreach
$input = [13 => 500, 16 => 1000];
$output = "";
foreach ($input as $k => $v) {
$output .= $k . " " . $v . ", ";
}
$output = rtrim($output, ", ");
var_dump($output);

This code will solve your issue.
$array = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach ($array as $key => $val) {
echo " ".$key ." ". $val." ,";
}

assuming you searching for a function with multiple pair array values (as you describe)
and each result should be the format: key1[sp]val1,[sp]key2[sp]val2 and you want an array of all these values to use later i did this function:
<?php
function ar(){
$a=func_get_args();
foreach($a as $ar){
$s='';
$i=0;
$s='';
foreach($ar as $ch =>$vl){
$s.=$ch.' '.$vl;
if($i<count($ar)-1){
$s.=', ';
}
$i++;
}
$res[]=$s;
}
return $res;
}
/* output values by sending multiple arrays to parse */
var_dump(ar(
[13 => 500,16=> 1000]
,[12 => 1,13 => 1111]
));
?>

Related

Recursively loop throught multidemensional array and keep track of parent array [duplicate]

This question already has answers here:
PHP recursive array searching
(3 answers)
Closed 2 years ago.
That's a short version of the array I'm working with:
Array
(
[orders] => Array
(
[0] => Array
(
[id] => 123
[email] => somemail#mail.com
[line_items] => Array
(
[0] => Array
(
[id] => 456
)
)
)
)
)
I'd like to loop through it and echo out every $key => $value pair but keep track of the "parent" array.
When using this function:
function recursive($array, $level = 0){
foreach($array as $key => $value){
if(is_array($value)){
recursive($value, $level + 1);
} else{
echo $key . ": " . $value, "\n";
}
}
}
i get:
id: 123
email: somemail#mail.com
id: 456
and I would like to keep the parent array in front of the values so that i know which id is echoed out.
orders_0_id: 123
orders_0_email: somemail#mail.com
line_items_0_id: 456
Updated working solution:
function recursive($array, $level = -1,array $parentKey = []){
foreach($array as $key => $value){
$newKey = array_merge($parentKey, [$key]);
if(is_array($value)){
recursive($value, $level + 1, $newKey);
} else{
$parent = implode('_', $newKey);
echo $parent . ": " . $value, "\n";
}
}
}
I think this is what you are looking for, but it might be too much information.
Given this array:
$data = [
'orders' => [
[
'id' => 123,
'email' => 'text#example.com',
'line_items' => [
[
'id' => 356,
],
],
],
],
];
You can keep track of the parent key in an array:
function dumper(array $array, array $parentKey = [])
{
foreach ($array as $key => $value) {
$newKey = array_merge($parentKey, [$key]);
if (is_array($value)) {
dumper($value, $newKey);
} else {
$s = implode('_', $newKey) . ": " . $value . "\n";
echo $s . PHP_EOL;
}
}
}
dumper($data);
This produces:
orders_0_id: 123
orders_0_email: text#example.com
orders_0_line_items_0_id: 356

Merge values in foreach loop based on preg match condition

I have been trying unsuccessfully to access and manipulate certain name value pairs within an array when in a foreach loop.
My data is in an array like this:
[0] => Array
(
[subject] => math
[price] => 5
[year] => 2006
)
[1] => Array
(
[subject] => reading
[price] => 7
[year] => 2007
[author] => Smith
[publisher] => Press
)
[2] => Array
(
[subject] => reading
[price] => 9
[year] => 2008
[author] => Jones
[copyright] => 1999
)
My code is:
$count = count($array);
for ($i = 0; $i < $count; $i++) {
foreach($array[$i] as $name => $value) {
if(preg_match('(subject|price|year)', $name) != 1) {
#$desc .= '-'.$name.'-'.$value;
} else {
$desc = '';
}
echo $i.' : '.$desc.'<br />';
}
}
My desired output from the code above would be:
0 : subject-math / price-5 / year-2006
1 : subject-reading / price-7 / year-2007 / author-Smith-publisher-Press
2 : subject-reading / price-9 / year-2008 / author-Jones-copyright-1999
The main issue I am facing is that I don't know how to combine & echo out all of the name value pairs that don't match the preg_match condition. Essentially subject, price and year and common to every record but any of the others I want to be able to access all merged together as one item.
Thanks in advance for any help!
This code will do what you want. It loops through your array, pushing all the key-value pairs into an array and then echo'ing an implode (with /) of the array. Values for subject, price and year have their own entries, while all other values are pushed into an array which is then also imploded using - to give your desired output. Rather than using preg_match to match keys, a simple in_array is used instead:
foreach ($data as $k => $d) {
$out = array();
foreach ($d as $key => $value) {
if (in_array($key, ['subject', 'price', 'year'])) {
$out[] = "$key-$value";
}
else {
$out['others'][] = "$key-$value";
}
}
if (isset($out['others'])) $out[] = implode('-', $out['others']);
unset($out['others']);
echo "$k : " . implode(' / ', $out) . "\n";
}
Output:
0 : subject-math / price-5 / year-2006
1 : subject-reading / price-7 / year-2007 / author-Smith-publisher-Press
2 : subject-reading / price-9 / year-2008 / author-Jones-copyright-1999
Demo on 3v4l.org
I guess, it'll be the most simple implementation:
foreach ($array as $index => $item)
{
$result = array_filter
([
'subject-' . array_shift($item),
'price-' . array_shift($item),
'subject-' . array_shift($item),
implode('-', $item)
]);
$result = implode(' / ', $result);
echo "$index: $result\n";
}

PHP Looping through a multi-dimensional array

Hi I have this multi dimensional array in PHP:
$team_arrays = array (
"lakers" => array (
24 => "Bryant",
6 => "Price",
17 => "Lin"
),
"knicks" => array (
7 => "Anthony",
22 => "Shumpert",
12 => "Jackson"
),
"thunder" => array (
35 => "Durant",
0 => "Westbrook",
13 => "Miller"
)
);
I wanted to display something like this:
Team Name: lakers
Bryant = 24
Price = 6
Lin = 17
Team Name: knicks
Anthony = 7
Shumpert = 22
Jackson = 12
...
This is the code that I tried but seems not to work:
foreach ($team_arrays as $names => $team) {
echo "<h2>Team Name: " . $names . "</h2>";
echo "<ol>";
foreach ($team_arrays as $jersey => $names) {
echo "<li>" . $names . " = " . $jersey . "</li>";
}
echo "</ol>";
}
It generates this kind of error
Notice: Array to string conversion in
Would anyone tries for a help. Please.
I found this solution from other question but seems I can't relate to it.
There is only one small problem in your code
foreach ($team_arrays as $jersey => $names) {
^ // again looping over the same outer array?
That inner loop is wrong, you should loop over $team and not $team_arrays because your outer loop picks up each team using $team variable.
foreach ($team as $jersey => $names) {
Rest of your code and logic is already fine.
Fiddle
You need to change this line from;
foreach ($team_arrays as $jersey => $names) {
to:
foreach ($team as $jersey => $names) {
Change to foreach ($team as $jersey => $names)
Try this :
$team_arrays = array (
"lakers" => array (
24 => "Bryant",
6 => "Price",
17 => "Lin"
),
"knicks" => array (
7 => "Anthony",
22 => "Shumpert",
12 => "Jackson"
),
"thunder" => array (
35 => "Durant",
0 => "Westbrook",
13 => "Miller"
)
);
foreach ($team_arrays as $names => $team) {
echo "<h2>Team Name: " . $names . "</h2>";
echo "<ol>";
foreach ($team as $jersey => $names) {
echo "<li>" . $names . " = " . $jersey . "</li> \n";
}
echo "</ol>";
}
?>

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 this PHP array to prepare an array without duplicate "terms" and combining?

I need to modify one PHP array and I really have hard time with it :(
Array ( [0] => product_category-big-savings [1] => product_category-for-men [2] => product_category-jeans [3] => brand-3-1-phillip-lim [4] => size-10 [5] => )
That is the array output, I want to convert it to be like this:
Array ( [product_category] => big-savings, for-men, jeans [brand] => 3-1-phillip-lim [size] => 10 )
I really can't get the hang of it. Here is what I have tried:
foreach($arr as $k => $v) {
if ($v != '') {
$arr = explode('-', $v, 2);
$terms[] = $arr[1];
$taxes[] = $arr[0];
}
}
The first array consists of keys/values. The values are the terms I am targetting: for example:
product_category-big-savings is my target and I use this to split the category from its value:
$arr = explode('-', $v, 2);
Which gives me:
product_category ->
big-savings ->
And so on. How to group all product categories after that in array with product_category as key? and so on.
But I get an even more complicated form after that. I assume there is a simple formula that rolls this array over and convert it in the desired format. any help appreciated pleasee...
list($key, $value) = explode('-', $v, 2);
if (isset($result[$key])) {
$result[$key] .= ', ' . $value;
} else {
$result[$key] = $value;
}
You should do this instead:
foreach($arr as $k => $v) {
if ($v != '') {
$arr = explode('-', $v, 2);
if (!isset($result[$arr[0]])){
$result[$arr[0]] = $result[$arr[1]];
}
else {
$result[$arr[0]] .= ', '.$result[$arr[1]];
}
}
}

Categories