This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 7 months ago.
I have 2 xPath requests :
$medias = $xpath->query("//strong//a[contains(#class, 'no')]");
$links = $xpath->query("//strong//a[contains(#class, 'no')]/#href");
My goal is to have only one array that contains something like this :
0 => array:1 [▼
"title" => "A besúgó"
"link" => "xyz"
]
I tried this
$i=0;
foreach($medias as $media)
{
$tab[]['titre'] = $media->textContent;
$i++;
}
$i=0;
foreach($medias as $media)
{
$tab[]['lien'] = $media->textContent;
$i++;
}
dd($tab);
But it's ugly and it does not work. Can you help ?
It's hard to understand what you are trying to achieve, but from what I can tell it is this.
$tab = [];
for ($i = 0; $i < count( $medias ); $i++ ) {
$tab[] = [ 'titre' => $medias[$i], 'lien' => $links[$i] ];
}
you may just use array_merge() function to merging more than 1 arrays
array_merge(array1, array2, array3, ...)
Related
I have country list in array with multiple array, like:
public static function listCountries()
{
$this->country = array(
array(1, 'SAD', 'sad.png'),
array(2, 'Argentina', 'argentina.png'),
array(3, 'Australija', 'australija.png'),
array(4, 'Novi Zenland', 'noviz.png'),
array(5, 'Belgija', 'belg.png'),
array(6, 'Nizozemska', 'nizozemska.png')
);
}
But when i do foreach for array, i'm getting this:
//From DB
$item->country = "1,4";
$item->country = explode(",", $item->country);
for($i=0; $i < count($item->country); $i++) {
$index = $item->country[$i];
if( !empty($this->country[$index]) ) {
$item->country[$i] = $this->country[$index];
}
}
$item->country = implode(",", $item->country);
echo $item->country;
But i'm getting something like this:
array:2 [▼
0 => array:3 [▼
0 => 5
1 => "Belgija"
2 => "belg.png"
]
1 => array:3 [▼
0 => 2
1 => "Argentina"
2 => "argentina.png"
]
]
1 = SAD, 4 = Novi Zenland, not Belgija and Argentina
There is no good country, also no data what i want. How to fix this?
You can use this foreach loop to go through the other array and swap the string if the number matches:
$item->country = "1,4";
$item->country = explode(",", $item->country);
for($i=0; $i < count($item->country); $i++) {
$index = $item->country[$i];
foreach($this->country as $c) {
if($c[0] == $index) {
$item->country[$i] = $c[1]; // or $item->country[$i] = $c; if you want all three items
break;
}
}
}
$item->country = implode(",", $item->country);
echo $item->country;
// Should output: SAD,Novi Zenland
The indexes in arrays are 0-based, which means that:
$index = $item->country[$i];
Has to become
$index = $item->country[$i - 1];
To correlate with the country ids. Otherwise, it is always one off. This is assuming that the ids are always ordered from least to greatest, and all ids are a continuous range.
My permutation/combinations of data
$combinations = [[]];
$data = [
['alteration1', 'alteration2', 'alteration3', 'alteration4' ... upto 5 each],
['alteration1', 'alteration5', 'alteration6', 'alteration7' ... upto 5 each],
['alteration8', 'alteration9', 'alteration10', 'alteration5' ... upto 5 each],
... upto 6 max
];
$length = count($data);
for ($count = 0; $count < $length; $count++) {
$tmp = [];
foreach ($combinations as $v1) {
foreach ($data[$count] as $v2)
$tmp[] = array_merge($v1, [$v2]);
}
$combinations = $tmp;
}
print_r($combinations);
The script would generate such sets
0 => array:3 [▼
0 => "alteration1"
1 => "alteration1"
2 => "alteration8"
]
1 => array:3 [▼
0 => "alteration1"
1 => "alteration1"
2 => "alteration9"
]
... the issue begins when I start getting the same sequences of data in my case array index 0 and 20 would be exactly the same despite any position.
20 => array:3 [▼
0 => "alteration8"
1 => "alteration1"
2 => "alteration1"
]
21 => array:3 [▼
0 => "alteration1"
1 => "alteration9"
2 => "alteration1"
]
$final = []; // remove duplicates
The basic idea is to keep $combinations array's unique (alteration1,alteration2,alteration3) is equal to (alteration3,alteration1,alteration2) therfore it should be skipped in the $final array. I haven't really found anything around SO and google. Thanks for the help. $data dimentions [ from 1 - 6 ], each array inside can be [ 1 - 6 ]. Following script might not be working as expected .
http://sandbox.onlinephpfunctions.com/code/3ad5084386c2185f7619aaac152b638873039ee8
We iterate over the data and find unique elements first for each set using array_unique.
We then natsort them to get a sorted form and serialize them using implode(). By doing this, we would get the same serialized code for sets ABC,CBA,BAC etc.
We then find duplicates using keys check inside a variable, say $set. If the serialized key is set, we exclude it from the results, else we include it in our final results.
Snippet:
<?php
$data = [
['alteration1', 'alteration4',],
['alteration2','alteration3'],
['alteration2','alteration3'],
[]
];
$combinations = [[]];
foreach($data as $index => $current_data){
$current_data = array_unique($current_data);
if(empty($current_data)) continue;
$temp_combinations = [];
foreach($current_data as $value){
foreach($combinations as $each_combination){
$temp_combinations[] = array_merge($each_combination,[$value]);
}
}
$combinations = $temp_combinations;
}
$set = [];
$unique_combinations = [];
foreach($combinations as $each_combination){
natsort($each_combination);
$serialized_form = implode(",",$each_combination);
if(isset($set[$serialized_form])) continue;
if(empty($each_combination)) continue;
$unique_combinations[] = $each_combination;
$set[$serialized_form] = true;
}
print_r($unique_combinations);
Demo: https://3v4l.org/Do6oH
This question already has answers here:
How to GROUP BY and SUM PHP Array? [duplicate]
(2 answers)
Closed 9 months ago.
I want to sum subarray values and group by a subarray value but I am getting error: 'Undefined index: EEReg'.
The array is as follows.
and the current code is;
$total_balances = array();
foreach ($balances as $balance) {
foreach ($balance as $key => $value) {
if ($key == 'MemberNumber' || $key == 'Portfolio') {
continue;
} else {
$total_balances[$balance['Portfolio']][$key] += $value;
}
}
}
I expect the result to be;
$total_balances = [
"Aggressive" => [
"EEReg" => "Sum of EEReg where Portfolio is Aggressive",
"ERReg" => "Sum of ERReg where Portfolio is Aggressive",
],
"Moderate" => [
"EEReg" => "Sum of EEReg where Portfolio is Moderate",
"ERReg" => "Sum of ERReg where Portfolio is Moderate",
]
]
You need to use foreach only once and also you need to define the keys in $total_balance array before using them. Please see below code
$total_balances = array();
foreach ($balances as $balance) {
if( !isset( $total_balances[$balance['Portfolio']] )) {
$total_balances[$balance['Portfolio']] = array('EEREG' => 0, 'ERREG' => 0);
}
$total_balances[$balance['Portfolio']]['EEREG'] += $balance['EEREG'];
$total_balances[$balance['Portfolio']]['ERREG'] += $balance['ERREG'];
}
This question already has answers here:
PHP: Adding prefix strings to array values
(4 answers)
Closed 5 years ago.
I have an array that needs some modification, I need to add a word before every value. Is there a easy way to do this?
[
'site'=>'some-slug-of-page',
'site'=>'some-slug-new-page',
'site'=>'my-page'
]
needs to be
[
'site'=>'blog/some-slug-of-page',
'site'=>'blog/some-slug-new-page',
'site'=>'blog/my-page'
]
For the sake of immutability, I create a new array, reusing the old keys.
$originalArr = [
'site1' => 'some-slug-of-page',
'site2' => 'some-slug-new-page',
'site3' => 'my-page'
];
$newArr = [];
foreach ($originalArr as $key => $value) {
$newArr[$key] = 'blog/' . $value;
}
array_walk($arr, function (& $val, $key) { $val = 'blog/' . $val;});
Edit :
i Want a structure like this
'categories' => [
[
'name' => "science" ,
'questions' => [
[
'question' => 'C1_Q2',
'answer' => 'C1_A2',
],
[
'question' => 'C1_Q3',
'answer' => 'C1_A3',
]
]
]
but with help of loop
I am trying to create a questionnaire in which 3 steps need to be done
Create 3 arrays
1.categories - 2d -- like category["science"]["questions"]
2.questions
3.answers
step 1. add 10 questions in question array and add 10 answers in answer arrays
step 2.first 5 question of question array should be inserted to categories["science"]["questions"] and 5 answers to categories["science"]
["answers"]
I created Question and answer array and added 10 , 10 elements in it . but didnt succeed to add its elements as per step2 . I tried few logic
$Category=array();
$Q=array();
$A=array();
for($i=1;$i<=10;$i++)
{
$Q[] = "Question post".$i;
$A[] = "Answer post".$i;
//if($i==5)
//{
// array_push($Category,$Q[i]);
// break;
//} ---logic not working
}
//array first 5 Questions to category array
/*
for($i=1;$i<=5;$i++)
{
//$Category[]=$Q[i];
array_push($Category,$Q[i]);
}
*/ -- not working
print_r($Category);
Any suggestion or help would be appreciated
Try this:
$questions = [];
$answers = [];
for($i=1; $i <= 10; $i++) {
$questions[] = 'Question post' . $i;
$answers[] = 'Answer post' . $i;
}
$categories = ['science', 'something', 'else'];
$result = [];
foreach ($questions as $index => $question) {
if ($index % 5 != 0 || $index == 0) {
$category = current($categories);
} else {
$category = next($categories);
}
$result[$category][] = ['question' => $question, 'answer' => $answers[$index]];
}
var_dump($result);