$array = array();
foreach( $order->get_items() as $item_id => $item ) {
$rray = array(
'name'=>$item['name'],
'qty'=>$item['qty']
);
$array[] = $rray;
}
}
I have the array like the above
How to create a string look like this:
'name qty, name qty, name qty, name qty, name qty, name qty, name qty, '
'Afghan Kush 1, Pomegranate Blue-Rasp 1, Blueberry Vanilla 1, Banana Strawberry 1, Caramel Cappuccino 1, '
Try with:
$array_text = implode(', ', array_map(function ($e) { return $e['name'] . ' ' . $e['qty']; }, $array));
$mystring = "";
foreach($array as $strain) {
$strain['array_text'] = $strain['name']." ".$strain['qty'];
$mystring .= $strain['array_text'].", ";
}
echo $mystrain;
You can use array_map() and implode().
$array = [
[
'name' => 'Blackberry Kush',
'qty' => '1'
],
[
'name' => 'Granddaddy Purple',
'qty' => '1'
],
[
'name' => '20% THC',
'qty' => '1'
],
[
'name' => 'Pomegranate Blue-Rasp',
'qty' => '1'
],
[
'name' => 'Blueberry Vanilla',
'qty' => '2'
],
[
'name' => 'Banana Strawberry',
'qty' => '3'
]
];
$formatted = array_map( function($obj) {
return "{$obj['name']} {$obj['qty']}";
}, $array );
echo implode( ', ', $formatted );
Example
$array = array();
foreach( $order->get_items() as $item_id => $item ) {
$rray = array(
'name'=>$item['name'],
'qty'=>$item['qty']
);
$array[] = $rray;
}
foreach($array as $key => $value) {
$result .= $value['name']." ". $value['qty'];
$result .= ", ";
}
var_dump($result);
Work like a champ!
Related
I have an array as
$apps = array(
array(
'id' => '2',
'name' => 'Popcorn'
),
array(
'id' => '1',
'name' => 'EveryCord'
),
array(
'id' => '2',
'name' => 'AirShou'
),
Here I want to print names where id="2". So I tried it with following code.
foreach ( $apps as $var ) if ($var['id'] == "2") {
echo $var['name']
}
The problem is that it only print first result of the array as
"Popcorn".
But I want to extract all result which are
"Popcorn and Airshou"
How can I fix this. Can someone help me !
Try this;
$apps = [
['name' => 'Fish', 'id' => 2],
['name' => 'Chips', 'id' => 1],
['name' => 'Sticks', 'id' => 2],
];
$using = [];
foreach ( $apps as $var ) {
if ($var['id'] == "2") {
$using[] = $var['name'];
}
}
echo implode(" and ", $using);
RESULT:
You can create a sample array.
And append the name to it, if it is id=2
Code:
$apps = [
['id' => '2', 'name' => 'Popcorn'],
['id' => '1', 'name' => 'EveryCord'],
['id' => '2', 'name' => 'AirShou']
];
$names = [];
if (! empty($apps)) {
foreach ($apps as $elem) {
if ($elem['id'] == 2) {
$names[] = $elem['name'];
}
}
}
$finalName = ! empty($names) ? implode(' and ', $names) : '';
echo '<pre>';print_r($finalName);echo '</pre>';
// Output: Popcorn and AirShou
You can filter the array on the item id and then retrieve the column name:
array_column(array_filter($apps, function($v){return '2' === $v['id'];}), 'name')
result:
array(2) {
[0] =>
string(7) "Popcorn"
[1] =>
string(7) "AirShou"
}
Change your loop by this code, and you will got both names,
foreach ( $apps as $var ){
if ($var['id'] == "2") {
echo $var['name'];
}
}
Just grab names in array then implode it like this:
$temp = array();
foreach ( $apps as $var ) if ($var['id'] == "2") {
$temp[] = $var['name']
}
echo implode(' and ', $temp);
I'm trying to wrap my head around how to accomplish this…
I have an that's something like:
$contributors = array(
[0] => array(
[name] => 'John',
[role] => 'author',
),
[1] => array(
[name] => 'Gail',
[role] => 'author',
),
[2] => array(
[name] => 'Beth',
[role] => 'illustrator',
),
)
I'm trying to use this information to construct a detailed byline, like:
Written by John and Gail. Designed by Beth.
I need to compare each role to the previous and next ones in order to:
Use a label before the first instance of each role
Separate multiple instances of the same role with a comma
Use "and" instead of a comma before the last instance of each role
I'm no PHP expert so I'm having a hard time figuring out how to approach this! I have a function to output the right label depending on the role, but it's the comparisons I can't seem to figure out. I've considered foreach and while loops, but neither seems up to the job. I've never used a for loop so I don't know if it applies.
Some additional background:
I'm working with WordPress and the Advanced Custom Fields plugin.
$contributors is the value of an ACF Repeater field, where name and role are subfields. (I've simplified the names to make things easier.)
You can group the array per role and use array_pop to remove the element. implode the remaining array elements and just append the popped value.
$contributors = array(
array(
"name" => 'John',
"role" => 'author',
),
array(
"name" => 'Gail',
"role" => 'author',
),
array(
"name" => 'Jose',
"role" => 'author',
),
array(
"name" => 'Thomas',
"role" => 'author',
),
array(
"name" => 'Beth',
"role" => 'illustrator',
),
array(
"name" => 'Mary',
"role" => 'producer',
),
array(
"name" => 'Criss',
"role" => 'producer',
),
);
//Grouped the names according to role
$grouped = array_reduce($contributors, function($c, $v) {
if ( !isset( $c[ $v['role'] ] ) ) $c[ $v['role'] ] = array();
$c[ $v['role'] ][] = $v['name'];
return $c;
}, array());
//Construct final Array
$final = array();
foreach( $grouped as $key => $group ) {
$last = array_pop( $group );
if ( count( $group ) == 0 ) $final[ $key ] = $last; /* One one name on the role, no need to do anything*/
else $final[ $key ] = implode( ", ", $group ) . " and " . $last;
}
echo "<pre>";
print_r( $final );
echo "</pre>";
This will result to:
Array
(
[author] => John, Gail, Jose and Thomas
[illustrator] => Beth
[producer] => Mary and Criss
)
You can now use it as
echo 'Written by ' . $final["author"] . '. Designed by ' . $final["illustrator"] . '. Produced by ' . $final["producer"];
And will result to:
Written by John, Gail, Jose and Thomas. Designed by Beth. Produced by
Mary and Criss
You can try like this -
$contributors = array(
array(
'name' => 'John',
'role' => 'author',
),
array(
'name' => 'Gail',
'role' => 'author',
),
array(
'name' => 'Ali',
'role' => 'author',
),
array(
'name' => 'Beth',
'role' => 'illustrator',
)
);
#This function prepare array to expected String
function PrepareArray($data){
$combined = '';
if (count($data)>1) {
$last = array_slice($data, -1);
$first = join(', ', array_slice($data, 0, -1));
$both = array_filter(array_merge(array($first), $last), 'strlen');
$combined = join(' and ', $both);
}else{
$combined = implode('', $data);
}
return $combined;
}
$authors = array();
$designers = array();
foreach ($contributors as $key => $value) {
if ($value['role']=='author') {
$authors[] = $value['name']; #Keep Authors name in Array
}else if ($value['role']=='illustrator') {
$designers[] = $value['name']; #Keep Designers name in Array
}
}
$authors = PrepareArray($authors);
$designers = PrepareArray($designers);
echo "Written by {$authors}. Designed by {$designers}.";
Output :
Written by John, Gail and Ali. Designed by Beth.
Try below code:
<?php
$contributors = array(
0 => array(
'name' => 'John',
'role' => 'author',
),
1 => array(
'name' => 'Gail',
'role' => 'author',
),
2 => array(
'name' => 'Beth',
'role' => 'illustrator',
),
3 => array(
'name' => 'Albert',
'role' => 'author',
),
);
$labels = ['author'=>'Written by', 'illustrator'=>'Designed by', 'producer'=>'Produced by'];
$new_contributors = [];
foreach($contributors as $cont){
$new_contributors[$cont['role']][] = $cont['name'];
}
$str = '';
foreach($labels as $role=>$label){
if(isset($new_contributors[$role]) && is_array($new_contributors[$role])){
$str .= ' '.$label.' ';
foreach($new_contributors[$role] as $key=>$new_contributor){
$count = count($new_contributors[$role]);
if(($count - $key) == 1 ){
$str .= ' and ';
$str .= $new_contributor;
}else if(($count - $key) == 2){
$str .= $new_contributor;
}else{
$str .= $new_contributor.', ';
}
}
}
}
echo $str;
I'm seem to be stuck on something..
What I'm trying to do: with the following sample data I'm trying to show the data first in category and then show the data in the subcategory.
Sample Data:
array('category'=> 'America',
'sub-category'=> 'Illinois',
'name'=>'John Doe');
array('category'=>'America',
'sub-category'=>'Wisconsin',
'name'=>'Jane Doe');
Basically like this:
America
Illinois
John Doe
Wisconsin
Jane Doe
I can do the category by using the following code:
foreach ($total_states as $key => $states) {
$states_category[$states['CATEGORY']]['category'] = $states['CATEGORY'];
$statest_category[$states['CATEGORY']]['name'][] = $states;
}
How can I break it down by sub-categories using that for loop?
I tested and come up with this code:
<?php
$datas = [
[
'category' => 'America',
'sub-category' => 'Illinois',
'name' => 'John Doe'
],
[
'category' => 'America',
'sub-category' => 'State',
'name' => 'John Doedf'
],
[
'category' => 'America',
'sub-category' => 'State',
'name' => 'ghghjgj Doe'
],
];
$newArray = [];
foreach($datas as $d)
$newArray[$d['category']][$d['sub-category']][] = $d['name'];
foreach($newArray as $country => $city) {
echo $country. '<br>';
foreach($city as $subcity => $users) {
echo "\t $subcity <br>";
foreach($users as $u)
echo "\t\t $u <br>";
}
}
Give a try to this:
Initial data:
$info = [
['category' => 'America',
'sub-category' => 'Illinois',
'name' => 'John Doe'],
['category' => 'America',
'sub-category' => 'Wisconsin',
'name' => 'Jane Doe']];
Foreach:
foreach ( $info as $array ){
foreach ( $array as $key => $value){
switch ( $key ){
case 'category' : {
echo $value . '<br>';
break;
}
case 'sub-category' : {
echo " " . $value . '<br>';
break;
}
case 'name' : {
echo " " . $value . '<br>';
break;
}
}
}
}
I want to avoid if it is possible foreach combined with if. I want to search the array, take out the matches and create new one base on result.
In this example I want to create separate arrays for each os -
$os1 = $array;
$os2 = $array...
Array looks like this:
$array = [
0 => [
'id' => 1,
'name' => 'name',
'os' => 1
],
1 => [
'id' => 2,
'name' => 'name',
'os' => 1
],
2 => [
'id' => 3,
'name' => 'name',
'os' => 2
],
3 => [
'id' => 3,
'name' => 'name',
'os' => 2
]
];
Use array_filter to reduce the input array to the expected result
$os = 1;
$data = array_filter($array, function($item) use ($os) {
return $item['os'] == $os;
});
The short one
$os1 = [];
$os2 = [];
$os3 = [];
foreach ($array as $item) {
${'os' . $item['os']}[] = array('id' => $item['id'], 'name' => $item[$name];
}
The better one
$os1 = [];
$os2 = [];
$os3 = [];
foreach ($array as $item) {
switch($item['os']) {
case 1:
$os1[] = array('id' => $item['id'], 'name' => $item[$name]);
break;
case 2:
$os2[] = array('id' => $item['id'], 'name' => $item[$name]);
break;
case 3:
$os3[] = array('id' => $item['id'], 'name' => $item[$name]);
break;
default:
throw new Exception('Unknown Os');
}
}
Also you maybe want to assign array($item['id'] => $item[$name]); instead of array('id' => $item['id'], 'name' => $item[$name]);
$os1 = [];
$os2 = [];
$os3 = [];
foreach ($array as $item) {
${'os' . $item['os']}[] = array($item['id'] => $item[$name]);
}
I have the following multidimensional array:
$userList = array(
0 => array('id' => 1000, 'first_name' => 'John', 'last_name' => 'Smith'),
1 => array('id' => 1001, 'first_name' => 'Sam', 'last_name' => 'Johnson'),
);
I want to convert it to the array like:
$userData = array(
1000 => 'John Smith',
1001 => 'Sam Johnson',
);
It's quite obvious for me how to implement this using foreach loop, but I wonder if it's possible to do this with PHP array functions like array_map or array_walk. Please use PHP 5.3 for the callback function. Thank you!
Since those functions only work on the array values, getting them to set the key in the new array is somewhat awkward. One way to do it is:
$arr = array_combine(
array_map(function ($i) { return $i['id']; }, $arr),
array_map(function ($i) { return "$i[first_name] $i[last_name]"; }, $arr)
);
This is a case where a foreach is much more appropriate.
A minor trick from the functional programming.
$arr = array_reduce(
$arr,
function ($result, $item) {
$result[$item['id']] = $item['first_name'] . ' ' . $item['last_name'];
return $result;
},
array()
);
See array_reduce().
Code:
<?php
function convertArray ( $array ) {
$newUserList = array();
foreach ( $array as $value ) {
$newUserList[ $value[ 'id' ] ] = $value[ 'first_name' ] . ' ' . $value[ 'last_name' ];
}
return $newUserList;
}
$userList = array(
0 => array( 'id' => 1000, 'first_name' => 'John', 'last_name' => 'Smith' ),
1 => array( 'id' => 1001, 'first_name' => 'Sam', 'last_name' => 'Johnson' )
);
$newUserList = convertArray( $userList );
?>
Output:
Array
(
[1000] => John Smith
[1001] => Sam Johnson
)