Replacing substrings of nested arrays with a value from another array - php

The loop below outputs from the $defaultValues ​​values, there are 2 nested arrays in this array which are "colors" and "lessons".
This loop also takes the substring values ​​from the $search array and replaces them with the values ​​from the $replace.
Question: How to replace nested array clause value "colors" and "lessons" from $defaultValues ​​
values: "colors"=>["4", "5", "6"] and "lessons" =>["7 " , " 8", "9"] from $replace"
I can't figure out how to do this, my current code outputs this:
Name: 1
Age: 2
Whe are u from: 3
Your favorite color: 4
Choose courses: 7
Your comment: 10
I would like the code to output this:
Name: 1
Age: 2
Whe are u from: 3
Your favorite color: 4,5,6
Choose courses: 7,8,9
Your comment: 10
$defaultValues = [
"name" => "Name: <div class='user'> write your name </div>",
"age" => "Age: <div class='age'> enter your age </div>",
"from" => "Whe are u from: <div class='from'> write where are you from </div>",
"colors" => ["Your favorite color: <div class='colors'> you didn't say your favorite color </div>"],
"lessons" => ["Choose courses: <div class='lessons'> you have not chosen any course </div>"],
"comment" => "Your comment: <div class='comment'> no comments </div>",
];
$search = [
"name" => "write your name",
"age" => "enter your age",
"from" => "write where are you from",
"colors" => ["you didn't say your favorite color"],
"lessons" => ["you have not chosen any course"],
"comment" => "no comments",
];
$replace = [
"name" => "1",
"age" => "2",
"from" => "3",
"colors" => ["4", "5", "6"],
"lessons" => ["7", "8", "9"],
"comment" => "10",
];
foreach($defaultValues as $key => $items){
echo "<div class='block'>";
if(is_array($items)){
foreach($items as $child){
$items = str_replace($search[$key], $replace[$key], $child);
}
}
echo $items = str_replace($search[$key], $replace[$key], $items);
echo "</div>";
}

If you meant to join the array of colors and lessons to create the string to replace the corresponding placeholders you may use the function implode
https://www.php.net/manual/en/function.implode.php
Here's the code fragment:
if(is_array($items)){
foreach($items as $child){
$replaceListImploded = implode(",", $replace[$key]);
$items = str_replace($search[$key], $replaceListImploded, $child);
}
}
The corresponding output:
<div class='block'>
Your favorite color: <div class='colors'> 4,5,6 </div>
</div>
<div class='block'>
Choose courses: <div class='lessons'> 7,8,9 </div>
</div>
Here's the whole snippet: https://onlinephp.io/c/098a6

You just need to use implode to parse the array into a comma-separated string for output!
<?php
// example code
$defaultValues = [
"name" => "Name: <div class='user'> write your name </div>",
"age" => "Age: <div class='age'> enter your age </div>",
"from" => "Whe are u from: <div class='from'> write where are you from </div>",
"colors" => ["Your favorite color: <div class='colors'> you didn't say your favorite color </div>"],
"lessons" => ["Choose courses: <div class='lessons'> you have not chosen any course </div>"],
"comment" => "Your comment: <div class='comment'> no comments </div>",
];
$search = [
"name" => "write your name",
"age" => "enter your age",
"from" => "write where are you from",
"colors" => ["you didn't say your favorite color"],
"lessons" => ["you have not chosen any course"],
"comment" => "no comments",
];
$replace = [
"name" => "1",
"age" => "2",
"from" => "3",
"colors" => ["4", "5", "6"],
"lessons" => ["7", "8", "9"],
"comment" => "10",
];
foreach($defaultValues as $key => $items){
echo "<div class='block'>";
$replace_item = (is_array($replace[$key]) ? implode(",", $replace[$key]) : $replace[$key]);
if(is_array($items)){
foreach($items as $child){
$items = str_replace($search[$key], $replace_item, $child);
}
}
echo $items = str_replace($search[$key], $replace_item, $items);
echo "</div>";
}

echo $items = is_array($search[$key]) ? implode(',', $replace[$key]) : str_replace($search[$key], $replace[$key], $items);
will output you looking for

Related

Group rows on one column and form nested subarray with other column

Here is the thing I trying deal with
I have array which looks like this and have duplicates
$products = [
[
"product_name" => "Adidas1",
"address" => "street 2"
],
[
"product_name" => "Adidas2",
"address" => "street 2"
],
[
"product_name" => "Adidas3",
"address" => "street 2"
],
[
"product_name" => "Adidas4",
"address" => "street 2"
],
[
"product_name" => "Nike1",
"address" => "street name1"
],
[
"product_name" => "Nike2",
"address" => "street name1"
]];
Result that I need to get is below .
I did try different ways to do it but still can bring it to the finel result that have to come up
$final_result = [
[
"address" => "street 2",
"products" => [
"addidas1",
"addidas2",
"addidas3",
"addidas4",
]
],
[
"address" => "street name1",
"products" => [
"Nike1",
"Nike2",
]
]
any suggestion how to do it ?
here is my best solution that I tried
$stor_sorted = array();
foreach ($products as $product) {
if (array_count_values($product) > 1) {
$stor_sorted[] = ["address" => $product['address'], "items" => [$product['product_name']]];
}
}
try this code
$products = [
[
"product_name" => "Adidas1",
"address" => "street 2"
],
[
"product_name" => "Adidas2",
"address" => "street 2"
],
[
"product_name" => "Adidas3",
"address" => "street 2"
],
[
"product_name" => "Adidas4",
"address" => "street 2"
],
[
"product_name" => "Nike1",
"address" => "street name1"
],
[
"product_name" => "Nike2",
"address" => "street name1"
]];
$final_result = [];
foreach ($products as $pr){
$original_key = array_search($pr['address'], array_column($final_result, 'address'), true);
if($original_key === false){
$temp_array['address'] = $pr['address'];
$temp_array['products'] = [$pr['product_name']];
$final_result[] =$temp_array;
}else{
$final_result[$original_key]['products'][] = $pr['product_name'];
}
}
your result will be in final_result array
Use address values as temporary keys in your result array.
When an address is encountered for the first time, cast the product name as an array within the row and store the row.
On subsequent encounters, merely push the product name into the group's subarray.
When finished, re-index the result with array_values().
Code: (Demo)
$result = [];
foreach ($products as $row) {
if (!isset($result[$row['address']])) {
$row['product_name'] = (array)$row['product_name'];
$result[$row['address']] = $row;
} else {
$result[$row['address']]['product_name'][] = $row['product_name'];
}
}
var_export(array_values($result));
Same output with a body-less foreach() using array destructuring: (Demo)
$result = [];
foreach (
$products
as
[
'address' => $key,
'address' => $result[$key]['address'],
'product_name' => $result[$key]['product_name'][]
]
);
var_export(array_values($result));
Same output with functional style programming and no new globally-scoped variables: (Demo)
var_export(
array_values(
array_reduce(
$products,
function($result, $row) {
$result[$row['address']]['product_name'] = $row['product_name'];
$result[$row['address']]['address'][] = $row['address'];
return $result;
}
)
)
);

Table list to be dynamic require with skip approach using multi arrays

I want to be build logic as with below desired result. I have multi arrays which to be listed in table as questionnaire along with skip approach.
Helps are definitely appreciated
Fiddle link also mentioned it :- http://phpfiddle.org/main/code/1sr6-kn5u
<?php
$users = array (
0 => array("user_id" => "217", "user_name" => "S", "id" => "33"),
1 => array("user_id" => "216", "user_name" => "A", "id" => "32"),
2 => array("user_id" => "215", "user_name" => "B", "id" => "31"),
);
$questions = array (
0 => array("text" => "Q1", "type" => "text", "qid" => "1"),
1 => array("text" => "Q2", "type" => "text", "qid" => "2"),
2 => array("text" => "Q3", "type" => "text", "qid" => "3"),
);
$answers = array (
0 => array("SRI" => "31", "qid" => "1", "answer" => "A1"),
1 => array("SRI" => "31", "qid" => "2", "answer" => "A2"),
2 => array("SRI" => "31", "qid" => "3", "answer" => "A3"),
3 => array("SRI" => "32", "qid" => "3", "answer" => "A3"),
4 => array("SRI" => "32", "qid" => "2", "answer" => "A2"),
5 => array("SRI" => "33", "qid" => "1", "answer" => "A1"),
6 => array("SRI" => "33", "qid" => "3", "answer" => "A3")
);
//echo "<pre>";
//print_r($users);
//print_r($questions);
//print_r($answers);
?>
<table border = 1>
<tr>
<th>
User
</th>
<?php
foreach($questions as $key => $Qval){
echo "<th>".$Qval['text']."</th>";
}
?>
</tr>
<?php
foreach($users as $key => $Uval){
echo "<tr>";
echo "<td>".$Uval['user_name']."</d>";
foreach($questions as $key => $Qval){
foreach($answers as $key => $Aval){
if (($Qval['qid'] == $Aval['qid']) && ($Uval['id'] == $Aval['SRI'])){
echo "<th>".$Aval['answer']."</th>";
}
}
}
echo "</tr>";
}
?>
</table>
Desired Result
You need to divise your problem in two steps :
detect if the user answer the current question or not
then display the result
foreach($users as $key => $Uval){
echo "<tr>";
echo "<td>".$Uval['user_name']."</d>";
foreach($questions as $key => $Qval){
$userAnswer = null ; // no user answer per default
foreach($answers as $key => $Aval){ // loop to find a user answer
if (($Qval['qid'] == $Aval['qid']) && ($Uval['id'] == $Aval['SRI'])){
$userAnswer = $Aval['answer']; // save the user answer
break ; // we found the user answer, no need to continue to loop over the remaining answers
}
}
// display the user answer, use a placeholder if none is found
echo '<td>' . (is_null($userAnswer) ? 'SKIP' : $userAnswer) . '</td>' ;
}
echo "</tr>";
}

How can i get the arrays from the JSON file Dynamically

I have Json file which contain alot of Arrays. How can i get the the array Dynamically for each person by name like the get Parameter.
JSON
[{
"Name": "Somename",
"Lastname": "somelastname",
"Address": "someaddress",
},
{
"Name": "Somename1",
"Lastname": "somelastname1",
"Address": "someaddress1",
},
{
"Name": "Somename2",
"Lastname": "somelastname2",
"Address": "someaddress2",
}}
PHP
<?php
error_reporting(0);
$json_file = file_get_contents('jsonfile.json');
$someArray = json_decode($json_file, true);
?>
HTML
<a href="product.php?post=name">
<h3 id="custompage"><?php echo $value["Name"]; ?>
<span><br><?php echo $value["Lastname"]; ?></span>
<span><?php echo $value["Address"]; ?></span>
</h3>
</a>
I don't know what exactly you need to do (find only one match, or fetch all), but this is for both :
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$array = array(
1 => array( "Name" => "Somename1", "Lastname" => "somelastname1", "Address" => "someaddress1"),
2 => array( "Name" => "Somename2", "Lastname" => "somelastname2", "Address" => "someaddress2"),
3 => array( "Name" => "Somename3", "Lastname" => "somelastname3", "Address" => "someaddress3"),
4 => array( "Name" => "Somename4", "Lastname" => "somelastname4", "Address" => "someaddress4")
);
$data1 = json_encode($array);
//var_dump($data1);
$data = json_decode($data1, true);
//var_dump(json_decode($data1));
$myname = "Somename3";
/* one liner to get one result */
if( array_search("$myname", array_column($data, 'Name')) == true ){ echo"[ $myname found ! ]"; } else { echo"[ no data match ! ]"; }
/* loop to get all results */
foreach($data as $user){
echo $user['Name'].' '.$user['Lastname'].' '.$user['Address'].'<br/>';
}
?>

How i can print Arrays with for each loop

<?php
$students = array(
"student1" => array(
"age" => 36,
"gender" => "male",
"qualification" => "Master",
),
"student2" => array(
"age" => 25,
"gender" => "male",
"qualification" => "BA",
),
"student3" => array(
"age" => 26,
"gender" => "male",
"qualification" => "BA",
),
"student4" => array(
"age" => 25,
"gender" => "male",
"qualification" => "BA",
),
"student5" => array(
"age" => 20,
"gender" => "male",
"qualification" => "Master",
),
"student6" => array(
"age" => 20,
"gender" => "male",
"qualification" => "F.A",
),
);
?>
And i need result like this.
Hello Student1
Your age is 36 and
Your gender is male and
Your qualification is Master.
Hello Student2
Your age is 25 and
Your gender is male and
Your qualification is BA.
I have try like this.
foreach($students as $key=>$value)
{
echo "Mr".$key."<br />";
foreach($value as $key=>$value)
{
echo" Your $key is $value and <br />";
}
}
And my result like this.
Hello Student1
Your age is 36 and
Your gender is male and
Your qualification is Master and
Hello Student2
Your age is 25 and
Your gender is male and
Your qualification is BA and
No need for that other foreach inside, you can just use one. Each copy of the sub array ($info), you will just have to call its indices.
foreach ($students as $name => $info) {
echo "
Hello $name, <br/>
Your age is: $info[age] <br/>
Your gender is: $info[gender] <br/>
Your qualification is: $info[qualification] <hr/>
";
}
But if you really want to go that two foreach route, yes you could add a condition in the second loop to prevent it from adding the superfluous and:
foreach ($students as $name => $info) {
echo "Hello $name ";
foreach($info as $att => $val) {
echo "Your $att is: $val ", (end($info) != $val) ? ' and ' : '<br/>';
}
}
Try with -
foreach($students as $key=>$value)
{
echo "Mr".$key."";
$count = 1;
foreach($value as $key=>$val)
{
echo" Your $key is $val";
if ($count != count($val)) {
echo " and ";
}
}
}
Try this code:
foreach($students as $key => $value) {
echo 'Hello ', $key, ' Your age is ', $value['age'], ' gender is ' . $value['gender'], ' and Your qualification is ', $value['qualification']
}
You can concat string with echo, but coma will be better for performance.

PHP multidimensional array

Here's a quickie for the pros:
How do I display Value 1, 2, 3 etc as it's in it's third array?
$meta_boxes = array
(
"checkbox" => array
(
"name" => "checkbox",
"title" => "",
"description" => "This is an example of a checkbox field.",
"type" => "checkbox",
"rows" => "",
"width" => "",
"options" => array
(
"1" => "Value 1",
"2" => "Value 2",
"3" => "Value 3"
)
),
$str = '';
foreach($meta_boxes['checkbox']['options'] as $k => $v) {
$str .= $v . "\n";
}
$meta_boxes['checkbox']['options']['1'] will give you the string "Value 1" from the array, and then you can do whatever you want with that value.
You should now be able to figure out how to access the other two.

Categories