What I'm trying to accomplish is to write a html string in a controller with array values being looped in it. So for example;
$content = "Your store, at location A, has these items added to them". add array loop here. "Do take note!";
My array would be as such
array (
0 =>
array (
'id' => '5db29b6d31c391731239bbdf',
'name' => 'Diamond bracelet (sample)',
'tags' =>
array (
0 => 'female',
1 => 'jewelry',
),
'category' => 'Accessories',
'sku' => '1029EHW',
'priceType' => 'Fixed',
'unitPrice' => 190,
'cost' => 90,
'trackStockLevel' => true,
'isParentProduct' => false,
),
1 =>
array (
'id' => '5db29b6d31c391731239bbdb',
'name' => 'Long-sleeved shirt(sample)(M)',
'tags' =>
array (
0 => 'tops',
1 => 'cotton',
),
'category' => 'Women\'s Apparel',
'sku' => 'ABC1234-M',
'priceType' => 'Fixed',
'unitPrice' => 47.170000000000002,
'cost' => 20,
'trackStockLevel' => true,
'isParentProduct' => false,
'parentProductId' => '5db29b6d31c391731239bbd4',
'variationValues' =>
array (
0 =>
array (
'variantGroupId' => '5db29b6d31c391731239bbd5',
'value' => 'M',
),
),
),
)
note that the array can have many instances of product_name and sku, or can have none.
How do i populate this in my string to be like;
$content = "Your store, at location A, has these items added to them, 1) asd, 2)def, 3)asf . Do take note!
Try this, I've used \sprintf for ease, check if the output serves your purpose.
<?php
function stringMethod(): string
{
$count = 0;
$arrayString = [];
$array = [['product_name' => 'abc', 'product_sku' => 'def'],['product_name' => 'abc', 'product_sku' => 'asd']];
foreach ($array as $value){
$count++;
$arrayString[] = sprintf('%s)%s', $count, $value['product_sku']);
}
$string = \implode(',', $arrayString);
return \sprintf("Your store, at location A, has these items added to them %s Do take note!", $string);
}
echo stringMethod();
Hope this will help you. try to do it in less number of lines
$content = "Your store, at location A, has these items added to them, ";
$productArray = array (0 => array ('id' => '5db29b6d31c391731239bbdf','name' => 'Diamond bracelet (sample)','tags' => array (0 => 'female',1 => 'jewelry',),'category' => 'Accessories','sku' => '1029EHW','priceType' => 'Fixed','unitPrice' => 190,'cost' => 90,'trackStockLevel' => true,'isParentProduct' => false,),1 => array ('id' => '5db29b6d31c391731239bbdb','name' => 'Long-sleeved shirt(sample)(M)','tags' => array (0 => 'tops',1 => 'cotton',),'category' => 'Women\'s Apparel','sku' => 'ABC1234-M','priceType' => 'Fixed','unitPrice' => 47.170000000000002,'cost' => 20,'trackStockLevel' => true,'isParentProduct' => false,'parentProductId' => '5db29b6d31c391731239bbd4','variationValues' => array (0 => array ('variantGroupId' => '5db29b6d31c391731239bbd5','value' => 'M'))));
foreach ($productArray as $key => $product) {
$content .= ($key+1).') '.$product['name'];
if (count($productArray)-1!=$key) {
$content .= ', ';
}
}
$content .= ". Do take note!";
$content = "Your store, at location A, has these items added to them,". $this->getItemList($collection) .". Do take note!"
# Somewhere else in the controller
protected function getItemList(Collection $collection): string
{
return $collection->pluck('name')
->merge($collection->pluck('sku'))
->map(function($item, $key) {
return ($key + 1) . ') ' . $item;
})
->implode(', ');
}
An easy solution would be
$content = "Your store, at location A, has these items added to them";
$array = array(0=>["product_name" => "abc", "product_sku" => "def"], 1=>['product_name' => 'kdkf', 'product_sku'=> 'ljbkj']);
for($i = 0; $i<count($array); $i++){
$content .= ($i+1).") ".$array[$i]['product_name].' '.$array[$i]['product_sku'].', ';
}
$content .= "Do take note.";
This way you're just constantly concatonating the string value in separate parts instead of trying to inject it in the middle of the parent string.
not tested, may be syntax errors
Related
I have this array :
(
[id] => block_5df755210d30a
[name] => acf/floorplans
[data] => Array
(
[floorplans_0_valid_for_export] => 0
[floorplans_0_title] => title 1
[floorplans_0_house_area] => 40m²
[floorplans_0_bedrooms] => 1
[floorplans_1_valid_for_export] => 1
[floorplans_1_title] => title xx
[floorplans_1_house_area] => 90m²
[floorplans_1_bedrooms] => 2
[floorplans_2_valid_for_export] => 1
[floorplans_2_title] => title 2
[floorplans_2_house_area] => 50m²
[floorplans_2_bedrooms] => 1
[floorplans] => 3
)
)
As we can see in the data, we have fields (floorplans_X_valid_for_export).
What I want to do is to get the data only when this field equal to 1.
So from the given example, I want to keep only these fields:
[floorplans_1_valid_for_export] => 1
[floorplans_1_title] => title xx
[floorplans_1_house_area] => 90m²
[floorplans_1_bedrooms] => 2
[floorplans_2_valid_for_export] => 1
[floorplans_2_title] => title 2
[floorplans_2_house_area] => 50m²
[floorplans_2_bedrooms] => 1
This is an odd schema, but it can be done by iterating through the array and searching for keys where "valid_for_export" equals 1, and then using another array of field "stubs" to get the associated items by a unique identifier of X in floorplans_X_valid_for_export
$array = [
'floorplans_0_valid_for_export' => 0,
'floorplans_0_title' => 'title 1',
'floorplans_0_house_area' => '40m²',
'floorplans_0_bedrooms' => 1,
'floorplans_1_valid_for_export' => 1,
'floorplans_1_title' => 'title xx',
'floorplans_1_house_area' => '90m²',
'floorplans_1_bedrooms' => '2',
'floorplans_2_valid_for_export' => 1,
'floorplans_2_title' => 'title 2',
'floorplans_2_house_area' => '50m²',
'floorplans_2_bedrooms' => 1,
'floorplans' => 3
];
$stubs = [
'floorplans_%s_valid_for_export',
'floorplans_%s_title',
'floorplans_%s_house_area',
'floorplans_%s_bedrooms'
];
$newArr = [];
foreach ($array as $key => $value) {
if (strpos($key, 'valid_for_export') && $array[$key] == 1) {
$intVal = filter_var($key, FILTER_SANITIZE_NUMBER_INT);
foreach ($stubs as $stub) {
$search = sprintf($stub, $intVal);
if (isset($array[$search])) {
$newArr[$search] = $array[$search];
} else {
// key can't be found, generate one with null
$newArr[$search] = null;
}
}
}
}
echo '<pre>';
print_r($newArr);
Working: http://sandbox.onlinephpfunctions.com/code/23a225e3cefa2dc9cc97f53f1cbae0ea291672c0
Use a parent loop to check that the number-specific valid_for_export value is non-empty -- since it is either 0 or non-zero.
If so, then just push all of the associated elements into the result array.
Some reasons that this answer is superior to the #Alex's answer are:
Alex's parent loop makes 13 iterations (and the same number of strpos() calls); mine makes just 3 (and only 3 calls of empty()).
$array[$key] is more simply written as $value.
Sanitizing the $key to extract the index/counter is more overhead than necessary as demonstrated in my answer.
Code (Demo)
$array = [
'floorplans_0_valid_for_export' => 0,
'floorplans_0_title' => 'title 1',
'floorplans_0_house_area' => '40m²',
'floorplans_0_bedrooms' => 1,
'floorplans_1_valid_for_export' => 1,
'floorplans_1_title' => 'title xx',
'floorplans_1_house_area' => '90m²',
'floorplans_1_bedrooms' => '2',
'floorplans_2_valid_for_export' => 1,
'floorplans_2_title' => 'title 2',
'floorplans_2_house_area' => '50m²',
'floorplans_2_bedrooms' => 1,
'floorplans' => 3
];
$labels = ['valid_for_export', 'title', 'house_area', 'bedrooms'];
$result = [];
for ($i = 0; $i < $array['floorplans']; ++$i) {
if (!empty($array['floorplans_' . $i . '_valid_for_export'])) {
foreach ($labels as $label) {
$key = sprintf('floorplans_%s_%s', $i, $label);
$result[$key] = $array[$key];
}
}
}
var_export($result);
Output:
array (
'floorplans_1_valid_for_export' => 1,
'floorplans_1_title' => 'title xx',
'floorplans_1_house_area' => '90m²',
'floorplans_1_bedrooms' => '2',
'floorplans_2_valid_for_export' => 1,
'floorplans_2_title' => 'title 2',
'floorplans_2_house_area' => '50m²',
'floorplans_2_bedrooms' => 1,
)
With that constructed data it might be hard (not impossble tho), hovewer i would suggest to change it to multidimensional arrays so you have something like:
[floorplans][0][valid_for_export] => 0
[floorplans][0][title] => title 1
[floorplans][0][house_area] => 40m²
[floorplans][0][bedrooms] => 1
[floorplans][1][valid_for_export] => 1
[floorplans][1][title] => title xx
[floorplans][1][house_area] => 90m²
Rought sollution
It is not the best approach, but it should work if you dont need anything fancy, and know that structure of data wont change in future
$keys = [];
$for($i=0;$i<$array['floorplans'];++$i) {
if(isset($array['floorplans_'.$i.'_valid_for_export']) && $array['floorplans_'.$i.'_valid_for_export']===1) {
$keys[] = $i;
}
}
print_r($keys);
How can I make the values of array comma separated values?
this is my array:
array(
'product_name' =>
0 => 'pn1',
1 => 'pn2'
'supply_product_name' =>
0 => 'ps1'
'custom_product_code' =>
0 => string 'cpc1'
)
how to achieve to look like these:
array(
'product_name' => 'pn1, pn2' ,
'supply_product_name' => 'ps1' ,
'custom_product_code' => 'cpc1'
)
Try these code:
$arr = array(
'product_name' => ['pn1', 'pn2'],
'supply_product_name' => ['ps1'],
'custom_product_code' => ['cpc1']
);
foreach($arr as $key => $val)
{
$arr[$key] = implode($val, ',');
}
var_dump($arr);
I'm have time overlap check inside while loop and I would also like to display events title with results which is in another array.
Without double foreach loop I can echo $event->title; and it displays all event titles. If I put array $event which has $event->title, inside foreach which I have for overlap testing it only displays first title.
I'm newbie PHP and I'm banging my head with complete solution for a couple of days now. Any help would be awesome :(
while (list(,$event_row) = each($events)) {
$event->loadEvent($event_row[0]);
foreach ($events as $thisevent) {
$event_array = array($event->id,$event->title);
$conflicts = 0;
foreach ($events as $thatevent) {
if ($thisevent[0] === $thatevent[0]) {
continue;
}
$thisevent_from = $thisevent[1];
$thisevent_ends = $thisevent[2];
$thatevent_from = $thatevent[1];
$thatevent_ends = $thatevent[2];
if ($thatevent_ends > $thisevent_from AND $thisevent_ends > $thatevent_from) {
echo $event->title;
$conflicts++;
echo "Event #" . $thisevent[0] . " overlaps with Event # " . $thatevent[0] . "\n";
}
}
if ($conflicts === 0) {
echo "Event #" . $thisevent[0] . " is OK\n";
}
}
}
Without double foreach var_export($event) displays all event arrays.
array( 'title' => 'Event 1', 'description' => 'Event description 1', 'contact' => 'event contact 1', 'url' => '', 'link' => '', 'email' => 'event#eventemail.com', 'picture' => '', 'color' => '#009933', 'catName' => 'Events', 'catDesc' => 'General events', 'startDate' => 1432918800, 'endDate' => 1432926000, 'startDay' => 29, 'startMonth' => 5, 'startYear' => 2015, 'endDay' => 29, 'endMonth' => 5, 'endYear' => 2015, 'recurStartDate' => NULL, 'recurEndDate' => NULL, 'id' => '11', 'catId' => 1, 'status' => true, 'recType' => '', 'recInterval' => 0, 'recEndDate' => 1432850400, 'recEndType' => 0, 'recEndCount' => 1, ))
And var_export($events) array displays three times all arrays with id, start date and end date:
array ( 0 => array ( 0 => '11', 1 => 1432918800, 2 => 1432926000, ), 1 => array ( 0 => '13', 1 => 1432918800, 2 => 1432926000, ), 2 => array ( 0 => '16', 1 => 1432926000, 2 => 1432929600, ), )
Thank you for looking into it and giving any possible solutions hints, ideas :)
I am having problem with session array variable
$_SESSION ['roomsInfo_' . $intHId] = $strRTypeArr;
It automatically destroy when land on the other page, by using the <form action=”booking_level.php”>
foreach ( $arrRoomInfo as $arrRoomDetails ) {
// occup details
$AdultNum = ( int ) $arrRoomDetails->AdultNum;
$ChildNum = ( int ) $arrRoomDetails->ChildNum;
// child ages details
$strChAgs = '';
if (property_exists ( $arrRoomDetails, 'ChildAges' )) {
$childAgs = $arrRoomDetails->ChildAges->ChildAge;
$arrChAge = array ();
foreach ( $childAgs as $chAgs ) {
$chAgs = $chAgs->attributes ();
$arrChAge [] = $chAgs ['age'];
}
$strChAgs = implode ( ":", $arrChAge );
}
// set array for all the above details
$strRTypeArr [$rtId] [$i] = array (
'myRoomSq' => $i,
'roomSeq' => $arrRmSeq,
'adults' => $AdultNum,
'child' => $ChildNum,
'childAges' => $strChAgs,
'maxGuests' => $maxGuests,
'maxChild' => $maxChild,
'name' => $rmName,
'HotelRoomTypeId' => $rtId,
'roomId' => $roomId,
'isPublish' => $isPublish,
'Occupancy' => array (
"attributes" => array (
'avrNgtlyRtComm' => $avrNgtlyRtComm,
'avrNightPrice' => $avrNtPr,
'bedding' => $bedding
),
"boardBase" => array (
'bbId' => $arrBrdBsId,
'bbName' => $arrBrdBsName,
'bbPrice' => $arrBrdBsPrice,
'bbPublishPrice' => $arrBrdBspBPrce,
'strBBaseExists' => $strBBaseExists
),
'PriceBreakdown' => $arrDay,
"dblBrDownPrTourico" => $dblBrDownPrTourico,
"dblTtlBrDownPr" => $dblTtlBrDownPr,
'Supplements' => $arrSupp
),
'Discount' => $arrDst,
'cancelPolicy' => $strCnlionHtml,
'arrCanPolicy' => $arrCanPolicy,
'arrChcrCanPolicy' => $arrChcrCanPolicy,
'chcr_cancelPolicy' => $chcrCancellation,
'curncy' => $strCurn
);
$i ++;
}
}
}
}
$_SESSION ['roomsInfo_' . $intHId] = $strRTypeArr;
How can I store in Session Array Variable in a MySQL database ?
Just make sure that you assign the array the way you assign a normal value and then store the array in your database.
$_SESSION['dArray'] = $strRTypeArr;
//for example:
$strRTypeArr[0][0] = array (
'myRoomSq' => 2.5,
'roomSeq' => "test this",
'adults' => true,
'child' => 5,
'childAges' => "test"
);
$strRTypeArr[0][1] = array (
'myRoomSq' => 3.5,
'roomSeq' => "this is another test",
'adults' => false,
'child' => 6,
'childAges' => "test"
);
$_SESSION['dArray'] = $strRTypeArr;
echo "<pre>";
print_r($_SESSION['dArray']);
echo "</pre>";
//Store this $_SESSION['dArray'] in your database
You can also use json_encode($_SESSION['dArray']); to store your array in the database.
when searching an element in a nested array, could i get back it's 1st level nesting index.
<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k, $search_query){
global $cnt;
if($v == $search_query){
/* i want the sub array index to be returned */
}
}
?>
i.e to say, if i'am searching 'victor', i would like to have 'dep1' as the return value.
Could anyone help ??
Try:
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($coll), RecursiveIteratorIterator::SELF_FIRST);
/* These will be used to keep a record of the
current parent element it's accessing the childs of */
$parent_index = 0;
$parent = '';
$parent_keys = array_keys($coll); //getting the first level keys like dep1,dep2
$size = sizeof($parent_keys);
$flag=0; //to check if value has been found
foreach ($iter as $k=>$val) {
//if dep1 matches, record it until it shifts to dep2
if($k === $parent_keys[$parent_index]){
$parent = $k;
//making sure the counter is not incremented
//more than the number of elements present
($parent_index<$size-1)?$parent_index++:'';
}
if ($val == $name) {
//if the value is found, set flag and break the loop
$flag = 1;
break;
}
}
($flag==0)?$parent='':''; //this means the search string could not be found
echo 'Key = '.$parent;
Demo
This works , but I don't know if you are ok with this...
<?php
$name = 'linda';
$col1=array ( 'dep1' => array ( 'fy' => array ( 0 => 'john', 1 => 'johnny', 2 => 'victor', ), 'sy' => array ( 0 => 'david', 1 => 'arthur', ), 'ty' => array ( 0 => 'sam', 1 => 'joe', 2 => 'victor', ), ), 'dep2' => array ( 'fy' => array ( 0 => 'natalie', 1 => 'linda', 2 => 'molly', ), 'sy' => array ( 0 => 'katie', 1 => 'helen', 2 => 'sam', 3 => 'ravi', 4 => 'vipul', ), 'ty' => array ( 0 => 'sharon', 1 => 'julia', 2 => 'maddy', ), ), );
foreach($col2 as $k=>$arr)
{
foreach($arr as $k1=>$arr2)
{
if(in_array($name,$arr2))
{
echo $k;
break;
}
}
}
OUTPUT :
dept2
Demo