Display the member of one array depending on the other array - php

i have an array i and i want to show the array values if the name of same array repeat in the another array and have true value
my arrays like this
$array1 = [
array(
'name' => internal_evidence
'price' => 30
'course_id' => 3
),
array(
'name' => international_evidence
'price' => 450
'course_id' => 3
),
array(
'name' => internal_evidence
'price' => 10
'course_id' => 1
),
array(
'name' => technical_evidence
'price' => 134
'course_id' => 3
),
];
$array2 = [
array(
'id' => 3
'name' => graphic
'price' => 150
'attr' => array(
'internal_evidence' => 'true',
'international_evidence' => 'false',
'technical_evidence' => 'true'
)
),
array(
'id' => 5
'name' => 3dmax
'price' => 300
'attr' => array(
)
),
array(
'id' => 1
'name' => ICDL
'price' => 480
'attr' => array(
'internal_evidence' => 'true',
)
),
];
i want to showing this all attr selected with true value in like this
also I want to sum price of array2 member and array1
<h2>graphic</h2>
<p>internal_evidence</p>
<p>technical_evidence</p>
<small>course price: 150</small>
<small>314</small> <!-- Price with selected evidence -->
<h2>3dmax</h2>
<small>course price: 300</small>
<!-- its not have attr evidence -->
<h2>ICDL</h2>
<p>internal_evidence</p>
<small>course price: 480</small>
<small>490</small> <!-- Price with selected evidence -->
i try this but its don`t work properly
$priceOfAttr = 0;
foreach($array2 as $key => $cat):
echo "<h2>{$cat['name']}</h2>";
foreach($array1 as $pr):
if($pr['course_id'] == $cat['id']):
foreach($cat['attr'] as $m => $optionV):
if($m == $pr['name'] && $optionV == "true"){
echo $m .'<br>';
$priceOfAttr += $pr['price'];
// echo "<small>{$cat['price']}</small><br>";
// echo $cat['price'] + $pr['price']. "<br>";
}
endforeach;
echo $priceOfAttr + $cat['price'] . '<br>';
endif;
endforeach;
echo '<br>';
endforeach;

I'd use a combination array_reduce and array_map to transform your data into what you need, then simply loop over that to display your view:
<?php
// Index your $array1 by [id][name]
$array1ByIdAndName = array_reduce($array1, static function ($byIdAndName, $entry) {
$byIdAndName[$entry['course_id']][$entry['name']] = $entry;
return $byIdAndName;
});
// Transform $array2's `attr` entries into attribute list + compute total price
$array2 = array_map(static function ($entry) use ($array1ByIdAndName) {
$entry['total_price'] = $entry['price'];
$entry['attr'] = array_reduce(array_keys($entry['attr']), static function ($attrs, $attrName) use ($array1ByIdAndName, &$entry) {
if ($entry['attr'][$attrName] === 'true') {
$attrs[] = $attrName;
$entry['total_price'] += $array1ByIdAndName[$entry['id']][$attrName]['price'];
}
return $attrs;
}, []);
return $entry;
}, $array2);
// Display your view
?>
<?php foreach ($array2 as $entry): ?>
<h2><?= $entry['name'] ?></h2>
<?php foreach ($entry['attr'] as $attrName): ?>
<p><?= $attrName ?></p>
<?php endforeach ?>
<small>course price : <?= $entry['price'] ?></small>
<?php if ($entry['total_price'] > 0): ?>
<small><?= $entry['total_price'] ?></small>
<?php endif ?>
<?php endforeach ?>
Demo: https://3v4l.org/nS3Gl

Related

PHP how to get value from multidimensional array?

I have an array in a class and want to obtain the 'Apple' key value ('iPhone').
I assume a for each loop needs to be used.
How would I go about doing this?
UPDATE: I also need to specify the customerType and productType key values.
class Products {
public function products_list() {
$customerType = 'national';
$productType = 'phones';
$phoneType = 'Apple';
$productsArr = array();
$productsArr[] = array(
'customerType' => 'national',
'productType' => array(
'phones' => array(
'Apple' => 'iPhone',
'Sony' => 'Xperia',
'Samsung' => 'Galaxy'
),
'cases' => array(
'leather' => 'black',
'plastic' => 'red',
),
),
'international' => array(
'phones' => array(
'BlackBerry' => 'One',
'Google' => 'Pixel',
'Samsung' => 'Note'
),
'cases' => array(
'leather' => 'blue',
'plastic' => 'green'
),
)
);
}
}
I have created a function that you can more or less give it any product and it will return the key and value from the array
<?php
class Products
{
public function products_list()
{
$customerType = 'national';
$productType = 'phones';
$phoneType = 'Apple';
$productsArr[] = array(
'customerType' => 'national', 'productType' => array(
'phones' => array(
'Apple' => 'iPhone',
'Sony' => 'Xperia',
'Samsung' => 'Galaxy'
),
'cases' => array(
'leather' => 'black',
'plastic' => 'red',
),
),
'international' => array(
'phones' => array(
'BlackBerry' => 'One',
'Google' => 'Pixel',
'Samsung' => 'Note'
),
'cases' => array(
'leather' => 'blue',
'plastic' => 'green'
),
)
);
echo $this->get_value($phoneType, $productsArr) .'<br>';
echo $this->get_value($customerType, $productsArr) .'<br>';
echo $this->get_value($productType, $productsArr) .'<br>';
}
function get_value($product, array $products)
{
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($products), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $key => $value) {
if (is_string($value) && ($key == $product)) {
return 'key ->' . $key .' value ->'.$value;
}
}
return "";
}
}
$phone_products = new Products();
$phone_products->products_list();
To use it within the class just call
$this->get_value($phoneType, $productsArr);
from without the class call
$phone_products = new Products();
echo ($phone_products->get_value($phoneType, $productsArr));
//output: key ->Apple value ->iPhone
NB: $phoneType, $productsArr will either be defined the methods they are being used in or passed from other methods or define global variables within the class.
If you want single entry:
echo $productsArr[0]['productType']['phones']['Apple']."<br />";
If there are multiple data, you can use foreach:
foreach ($productsArr as $prod){
echo $prod['productType']['phones']['Apple']."<br />";
}
just try
foreach($productsArr[0]['productType']['phones'] as $phones){
echo $phones[$phoneType]; }
foreach($productsArr as $key1 => $data1 ){
if(is_array($data1))
foreach($data1 as $key2 => $data2 ){
if(is_array($data2))
foreach($data2 as $key3 => $data3 ){
if(array_key_exists('Apple', $data3)) {
echo $data3['Apple'] ."\n";
}
}
}
}

How can I pass an array of hidden informations in a POST request in Cake 3.2?

I have created a form for a POST request, but I need to send an array of information that must be not visible in that form.
The array consist in a not specified number of other arrays.
My array is called "$dati" and is made by a not bounded number of arrays with three information each.
The code of my form is:
<?= $this->Form->create(null,['type'=> 'post', 'url'=>['action'=>'selectForSell2',$rassegnaselezionata->id,$showselezionato->id,$proiezioneselezionata->id ]]) ?>
<?= $this->Form->input('stato', ['options' => ['tutti' => 'Tutti i Soci', 'firmato' => 'Soci Firmati', 'approvato' => 'Soci Approvati'] ] ); ?>
<?= $this->Form->input('campo', ['options' => ['cognome' => 'Cognome', 'nome' => 'Nome', 'codicefiscale' => 'Codice Fiscale'] ] ); ?>
<?= $this->Form->input('ricerca', ['label' => false, "class" => " form-control input-medium", "placeholder" => __('Ricerca'), 'visible'=>false]); ?>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
In my projects, I have the following element as hidden.ctp:
if (isset($model)) {
$model .= '.';
} else {
$model = '';
}
foreach ($fields as $field => $values) {
if (is_array($values)) {
echo $this->element('hidden', ['model' => $model . $field, 'fields' => $values]);
} else {
echo $this->Form->hidden($model . $field, ['value' => $values]);
}
}
Then you can just call it with
echo $this->element('hidden', ['fields' => $dati]);
If you want to hidden the value of the array then you can do it in this way.
<?php
$a = array("Name" => "Peter", "Age" => "41", "Country" => "USA");
?>
<input type="hidden" name="data[Menu][arr]" value="<?php pr($a); ?>">
It can produce output like,when you post the data.Check it.it is required or not
Array
(
[Menu] => Array
(
[arr] => Array( [Name] => sradha [Age] => 20 [Country] => IN)
)
)

PHP Get all alike values from array

I've got an multidimensional array with some values.
[
1 => [
'label' => 'SEO',
'content' => 'Some content',
'group' => 'We can offer'
]
2 => [
'label' => 'Webdesign',
'content' => 'Some content',
'group' => 'We can offer'
]
3 => [
'label' => 'Contact',
'content' => 'Some content',
'group' => 'Who are we?'
]
4 => [
'label' => 'Logodesign',
'content' => 'Some content',
'group' => 'We can offer'
]
5 => [
'label' => 'Address',
'content' => 'Some content',
'group' => 'Who are we?'
]
]
The group element is a variety of user input. I want to sort all group elements what are the same into the same array. It's then going to be displayed. If there are only 2 elements with the same group value, then there will only be two columns (50% width on both) in a .row element in HTML, if there are 1 element, only one column (100% width). I'm trying to build a very simple CMS if anyone was wondering why. There may be more easier ways to do this, but I can't think of any.
Any help is appreciated.
EDIT:
I just got the array sorted i think. It looks right.
Now I just need to display it the right way.
$i = 0;
$count = count($data['sections']);
$content = [];
for ($i = 0; $i < $count; $i++) {
if (!in_array($data['sections'][$i]['group'], $content)) {
$content[] = $data['sections'][$i]['group'];
}
$content[$data['sections'][$i]['group']][] = ['label' => $data['sections'][$i]['label'], 'content' => $data['sections'][$i]['content']];
}
Group the array
Simply loop through the array and put all the elements into a new, nested array:
$content = array();
foreach($data['sections'] as $section) {
$content[$section['group']][] = $section;
}
This gives you an array $content of this format:
[
'We can offer' => [
1 => [
'label' => 'SEO',
'content' => 'Some content',
'group' => 'We can offer'
]
2 => [
'label' => 'Webdesign',
'content' => 'Some content',
'group' => 'We can offer'
]
...
]
'Who are we?' => [
...
]
]
Divide the width: Table display
So how do you output this so that every category gets equal width? First you need to loop through the nested array to print some HTML:
<div class="outer">
<?php foreach($content as $group) { ?>
<div class="row">
<?php foreach($group as $item) { ?>
<div class="item"><?php echo $item['content']; ?></div>
<?php } ?>
</div>
<?php } ?>
</div>
Have a look at this answer for one way to do it using CSS:
div.outer { display:table; }
div.row { display:table-row; }
div.item { display:table-cell; }
Divide the width: Explicit width
Another way to do it is to calculate the width in percentage in PHP and set it explicitly with the width attribute:
<?php foreach($content as $group) { ?>
<div class="row">
<?php $w = 100 / count($group); ?>
<?php foreach($group as $item) { ?>
<div class="item" width="<?php echo $w; ?>%">
<?php echo $item['content']; ?>
</div>
<?php } ?>
</div>
<?php } ?>

Can you compare an array of strings in PHP and if there are two that are the same it will only return it once?

Here is the script I am running and I would like if there are 2 strings that the same to only display one string and not both. I dont know where to add the array_unique() I have added it to my script but it doesnt seem to work properlly, instead it is taking out all the strings with the same value Here is the script I am running and I would like if there are 2 strings that the same to only display one string and not both
//Get slider data from theme options
$company1 = $data['md_media_company_img1'];
$company2 = $data['md_media_company_img2'];
$company3 = $data['md_media_company_img3'];
$company4 = $data['md_media_company_img4'];
$company5 = $data['md_media_company_img5'];
$company6 = $data['md_media_company_img6'];
$company7 = $data['md_media_company_img7'];
$company8 = $data['md_media_company_img8'];
$company9 = $data['md_media_company_img9'];
$company10 = $data['md_media_company_img10'];
$company11 = $data['md_media_company_img11'];
$company12 = $data['md_media_company_img12'];
/*Slides Array*/
$company_name = array(
'company1' => array(
'name' => $company1,
),
'company2' => array(
'name' => $company2,
),
'company3' => array(
'name' => $company3,
),
'company4' => array(
'name' => $company4,
),
'company5' => array(
'name' => $company5,
),
'company6' => array(
'name' => $company6,
),
'company7' => array(
'name' => $company7,
),
'company8' => array(
'name' => $company8,
),
'company9' => array(
'name' => $company9,
),
'company10' => array(
'name' => $company10,
),
'company11' => array(
'name' => $company11,
),
'company12' => array(
'name' => $company12,
)
);
/*check if exist slide*/
$check_exist_company = 0;
$result = array_unique($company_name);
foreach($result as $company => $value) {
if (!empty ($value['name'])){
$check_exist_company = 1;
}
}
?>
<?php if($check_exist_company == 1) {// check if any slide image added in theme option, return custom slide?>
<?php $i = 1; ?>
<?php foreach($company_name as $company => $value) {
if (!empty ($value['name'])) {?>
<li><a class="nivoLink4" rel="<?php echo $i;?>" href="#"><?php echo $value['name'];?></a></li>
<?php ++$i ?>
<?php } ?>
<?php }?>
<?php } ?>
<!--/slider-->
You could just run array_unique() on the source array and just iterate over the result.

How retrieve specific duplicate array values with PHP

$array = array(
array(
'id' => 1,
'name' => 'John Doe',
'upline' => 0
),
array(
'id' => 2,
'name' => 'Jerry Maxwell',
'upline' => 1
),
array(
'id' => 3,
'name' => 'Roseann Solano',
'upline' => 1
),
array(
'id' => 4,
'name' => 'Joshua Doe',
'upline' => 1
),
array(
'id' => 5,
'name' => 'Ford Maxwell',
'upline' => 1
),
array(
'id' => 6,
'name' => 'Ryan Solano',
'upline' => 1
),
array(
'id' =>7,
'name' => 'John Mayer',
'upline' => 3
),
);
I want to make a function like:
function get_downline($userid,$users_array){
}
Then i want to return an array of all the user's upline key with the value as $userid. I hope anyone can help. Please please...
You could do it with a simple loop, but let's use this opportunity to demonstrate PHP 5.3 anonymous functions:
function get_downline($id, array $array) {
return array_filter($array, function ($i) use ($id) { return $i['upline'] == $id; });
}
BTW, I have no idea if this is what you want, since your question isn't very clear.
If you need do search thru yours array by $id:
foreach($array as $value)
{
$user_id = $value["id"];
$userName = $value["name"];
$some_key++;
$users_array[$user_id] = array("name" => $userName, "upline" => '1');
}
function get_downline($user_id, $users_array){
foreach($users_array as $key => $value)
{
if($key == $user_id)
{
echo $value["name"];
...do something else.....
}
}
}
or to search by 'upline':
function get_downline($search_upline, $users_array){
foreach($users_array as $key => $value)
{
$user_upline = $value["upline"];
if($user_upline == $search_upline)
{
echo $value["name"];
...do something else.....
}
}
}
Code :
function get_downline($userid,$users_array)
{
$result = array();
foreach ($users_array as $user)
{
if ($user['id']==$userid)
$result[] = $user['upline'];
}
return result;
}
?>
Example Usage :
get_downline(4,$array);

Categories