Drupal - get value from array - php

Maybe it's me but I can't get the values from the following array:
http://picpaste.com/pics/Untitled-2YV5V2Im.1427134235.png
What I want is to create a table where the headers are like this:
HomeTeam name | AwayTeam name | Match home_goals | Match away_goals
and then I have 9 rows with values.
My code so far:
$json = json_decode($server_output, true);
$days= $json['Calendar']['championship']['StageRound'][0]['matches'];
$header = ['HomeTeam name', 'AwayTeam name', 'Match home_goals', 'Match away_goals'];
$row = array();
foreach ($days as $key => $value) {
... here, I get always an error saying 'HomeTeam' is not an index...
}
$table = theme('table', array('header' => $header, 'rows' => $rows));
return $table;
Any help?
Thanks!
EDIT:
Added this code:
foreach ($days as $key => $value) {
$hometeam = $days[0]['HomeTeam']['name'];
$awayteam= $days[0]['AwayTeam']['name'];
dpm($hometeam . ' - ' . $awayteam);
}
I have the index [0] in both lines inside the for cycle but I need it to be from 0 to 9 (the lenght of the array. That would solve my problem.

Foreach is already iterating trough that matches array, so you don't need that [0]. Go with:
$hometeam = $value['HomeTeam']['name'];
$awayteam= $value['AwayTeam']['name'];
or
$hometeam = $days[$key]['HomeTeam']['name'];
$awayteam= $days[$key]['AwayTeam']['name'];
if you like to access array over key...

Related

calculate the sum of values based on the input and match

To calculate the sum of values based on the input and match it with names in an array
$input = '500';
$array1 = array("200" => 'jhon',"300" => 'puppy',"50" => 'liza',
"150" => 'rehana',"400" => 'samra',"100" => 'bolda',);
need answer like this output
jhon,puppy and bolda,rehana
This code creates an array $data that contains names and their respective values. It then uses a foreach loop to iterate through the array and subtract the value of each name from the input until the input becomes zero. The names of all the values that were subtracted from the input are stored in an array $names. Finally, if the array $names is not empty, the names are echoed using implode separated by "and". If the array is empty, it means no match was found and a message "No match found" is echoed.
So I'm going to go out on a guess here. (this sounds like cheating on homework lmao).
You need to output pairs of names where the two names add upto 500 (the input).
This probably wont be the most optimal solution, but it should be a solution that works?
$input = 500;
// using shorthand array formatting
$array1 = [
200 => 'jhon',
300 => 'puppy',
50 => 'liza',
150 => 'rehana',
400 => 'samra',
100 => 'bolda'
];
// create an array that holds names we have already processed.
$namesProcessed = [];
// loop over the names trying to find a compatible partner
foreach ($array1 as $points => $name) {
foreach ($array1 as $pointsPotentialPartner => $namePotentialPartner) {
// Don't partner with yourself...
if ($name == $namePotentialPartner) {
continue;
}
// Don't partner with someone that has already been processed.
if (in_array($namePotentialPartner, $namesProcessed)) {
continue;
}
// test if the two partners add up to the input
if ($input == ($points + $pointsPotentialPartner)) {
// if this is the first partner set, don't put in 'and'
if (count($namesProcessed) == 0) {
echo $name . ', ' . $namePotentialPartner;
} else {
echo ' and ' . $name . ', ' . $namePotentialPartner;
}
$namesProcessed[] = $name;
$namesProcessed[] = $namePotentialPartner;
}
}
}
Hope this helps.

Parse formatted strings containing 3 delimiters to create multiple flat arrays

I have strings in following format:
$strings[1] = cat:others;id:4,9,13
$strings[2] = id:4,9,13;cat:electric-products
$strings[3] = id:4,9,13;cat:foods;
$strings[4] = cat:drinks,foods;
where cat means category and id is identity number of a product.
I want to split these strings and convert into arrays $cats = array('others'); and $ids = array('4','9','13');
I know that it can be done by foreach and explode function through multiple steps. I think I am somewhere near, but the following code does not work.
Also, I wonder if it can be done by preg_match or preg_split in fewer steps. Or any other simpler method.
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
foreach($temps as $temp) {
$tempnest = explode(':', $temp);
$array[$tempnest[0]] .= explode(',', $tempnest[1]);
}
}
My desired result should be:
$cats = ['others', 'electric-products', 'foods', 'drinks';
and
$ids = ['4','9','13'];
One option could be doing a string compare for the first item after explode for cat and id to set the values to the right array.
$strings = ["cat:others;id:4,9,13", "id:4,9,13;cat:electric-products", "id:4,9,13;cat:foods", "cat:drinks,foods"];
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
$cats = [];
$ids = [];
foreach ($temps as $temp) {
$tempnest = explode(':', $temp);
if ($tempnest[0] === "cat") {
$cats = explode(',', $tempnest[1]);
}
if ($tempnest[0] === "id") {
$ids = explode(',', $tempnest[1]);
}
}
print_r($cats);
print_r($ids);
}
Php demo
Output for the first item would for example look like
Array
(
[0] => others
)
Array
(
[0] => 4
[1] => 9
[2] => 13
)
If you want to aggregate all the values in 2 arrays, you can array_merge the results, and at the end get the unique values using array_unique.
$strings = ["cat:others;id:4,9,13", "id:4,9,13;cat:electric-products", "id:4,9,13;cat:foods", "cat:drinks,foods"];
$cats = [];
$ids = [];
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
foreach ($temps as $temp) {
$tempnest = explode(':', $temp);
if ($tempnest[0] === "cat") {
$cats = array_merge(explode(',', $tempnest[1]), $cats);
}
if ($tempnest[0] === "id") {
$ids = array_merge(explode(',', $tempnest[1]), $ids);
}
}
}
print_r(array_unique($cats));
print_r(array_unique($ids));
Output
Array
(
[0] => drinks
[1] => foods
[3] => electric-products
[4] => others
)
Array
(
[0] => 4
[1] => 9
[2] => 13
)
Php demo
I don't generally recommend using variable variables, but you are looking for a sleek snippet which uses regex to avoid multiple explode() calls.
Here is a script that will use no explode() calls and no nested foreach() loops.
You can see how the \G ("continue" metacharacter) allows continuous matches relative the "bucket" label (id or cat) by calling var_export($matches);.
If this were my own code, I'd probably not create separate variables, but a single array containing id and cat --- this would alleviate the need for variable variables.
By using the encountered value as the key for the element to be added to the bucket, you are assured to have no duplicate values in any bucket -- just call array_values() if you want to re-index the bucket elements.
Code: (Demo) (Regex101)
$count = preg_match_all(
'/(?:^|;)(id|cat):|\G(?!^),?([^,;]+)/',
implode(';', $strings),
$matches,
PREG_UNMATCHED_AS_NULL
);
$cat = [];
$id = [];
for ($i = 0; $i < $count; ++$i) {
if ($matches[1][$i] !== null) {
$arrayName = $matches[1][$i];
} else {
${$arrayName}[$matches[2][$i]] = $matches[2][$i];
}
}
var_export(array_values($id));
echo "\n---\n";
var_export(array_values($cat));
All that said, I probably wouldn't rely on regex because it isn't very readable to the novice regex developer. The required logic is much simpler and easier to maintain with nested loops and explosions. Here is my adjustment of your code.
Code: (Demo)
$result = ['id' => [], 'cat' => []];
foreach ($strings as $string) {
foreach (explode(';', $string) as $segment) {
[$key, $values] = explode(':', $segment, 2);
array_push($result[$key], ...explode(',', $values));
}
}
var_export(array_unique($result['id']));
echo "\n---\n";
var_export(array_unique($result['cat']));
P.s. your posted coding attempt was using a combined operator .= (assignment & concatenation) instead of the more appropriate combined operator += (assignment & array union).

Assigning $i to the other variable in PHP

Hello guys i have seen a code which is really confusing for me ...THe code is .
function mysql_fetch_array_nullsafe($result) {
$ret=array();
$num = mysql_num_fields($result);
if ($num==0) return $ret;
$fval = mysql_fetch_row ($result);
if ($fval === false) return false;
$i=0;
while($i<$num)
{
$fname[$i] = mysql_field_name($result,$i);
$ret[$i] = $fval[$i]; // enum
$ret[''.$fname[$i].''] = $fval[$i]; // assoc
$i++;
}
return $ret;
}
here $ret[$i] = $fval[$i]; is assigned ..My question is that i just want to know why we are assigning $i to the variblar $ret..How it works ?..Is the value of $i stored to $ret or $i act as an index of $ret ..
Please help me to understand this ..Thanks in advance ..:)
I think variable $i is for the keys of array variable $ret.
'An array in PHP is actually an ordered map.'
So there's no numeric index in php array, unlike other language. $i is just a hashmap key that turns out to be an integer.
Reference: http://www.php.net/manual/en/language.types.array.php
$i is just a counter, so you might end up with arrays similar to those:
// $fname[$i] = mysql_field_name($result,$i);
$fname[1] => 'field 1';
$fname[2] => 'field 2';
$fname[3] => 'field 3';
// $ret[$i] = $fval[$i];
$ret[1] => 'value1';
$ret[2] => 'value2';
$ret[3] => 'value3';
// $ret[''.$fname[$i].''] = $fval[$i]; // assoc
$ret['field 1'] => 'value1';
$ret['field 2'] => 'value2';
$ret['field 3'] => 'value3';
Who ever thought up those lines of code wanted to be able to look up values using both index and field name:
$data = $ret[1];
$data = $ret['field 1']; //Those would both give the same result ('value1').
$i acts as the column number from mysql, see illustration below.
|id | name | lastname | address |
| 1 | john | doe | USA |
the id will be 0,name will be 1,lastname will be 2, and address will be 3
$ret array used to store the whole sql row from the mysql database.
where are assigning $i to $ret to retrieve the data from mysql row.

Take the value from array in php and explode

I have this the values of in my array as
$itsthere = (item1-0-100, item2-0-50, item3-0-70, item4-0-50, item5-0-100);
If the user enter the value item3 he has to get 70 which is present in array. I tried alot using explode but its not showing proper value. Can any one help me.
Try with:
$itsthere = array(
'item1-0-100',
'item2-0-50',
'item3-0-70',
'item4-0-50',
'item5-0-100'
);
$search = 'item3';
$output = '';
foreach ( $itsthere as $value ) {
if ( strpos($search . '-', $value) === 0 ) {
$output = explode('-', $value)[2];
break;
}
}
When you say item3 are you refering to the third position or the item3 as array key? I think you can create a assoc array and make item names as key
$isthere = array('item1' => '0-100', 'item2' => '0-50' ,'item3' => '0-70', ....,);
echo $isthere['item3']; // This would give you the value.
If you only want to know if this key is in the array use array_key_exists.
Try this :
$item = 'item3';
$itsthere = array('item1-0-100', 'item2-0-50', 'item3-0-70', 'item4-0-50', 'item5-0-100');
foreach($itsthere as $there)
{
$exp = explode('-',$there);
if($exp[0] == 'item3') {
echo $val = $exp[2];
};
}

How can I efficiently search a field for flipped word order?

I have the following array.
$arr = array('foo','bar','foo-bar','abc','def','abc-def','ghi','abc-def-ghi');
I'm given a new string to decide to add to the array or not. If the string is already in the array, don't add it. If it is not in the array in its current form, but in a flipped word form is found, don't add it.
How should I accomplish this?
Examples:
'foo' —-> N - Do NOT add, already found
'xyz' —-> Y - Add, this is new
'bar-foo' —-> N - Do NOT add, already found in the flipped form 'foo-bar'
'ghi-jkl' —-> Y - Add, this is new
What do you recommend?
If you want to exclude items whose elements ('abc','ghi', etc.) are contained in another order and not only reversed, you could do:
$arr = array('foo','bar','foo-bar','abc','def','abc-def','ghi','abc-def-ghi');
function split_and_sort($str) {
$partsA = explode('-', $str);
sort($partsA);
return $partsA;
}
$arr_parts = array_map('split_and_sort', $arr);
$tests = array('foo','xyz','bar-foo','ghi-jkl');
$tests_parts = array_map('split_and_sort', $tests);
foreach($tests_parts as $test) {
if( !in_array($test, $arr_parts)) {
echo "adding: " . join('-', $test) . "\n";
$arr[] = join('-', $test);
}
else {
echo "skipping: " . join('-', $test) . "\n";
}
}
var_export($arr);
which outputs:
skipping: foo
adding: xyz
skipping: bar-foo
adding: ghi-jkl
array (
0 => 'foo',
1 => 'bar',
2 => 'foo-bar',
3 => 'abc',
4 => 'def',
5 => 'abc-def',
6 => 'ghi',
7 => 'abc-def-ghi',
8 => 'xyz',
9 => 'ghi-jkl',
)
Heres a suggestions on one way you can try...
for each string in $arr, reverse it as push into another array called $rev_arr
then...
$new_array = array();
foreach ($arr as $arr_1) $new_array[$arr_1] = true; // just set something
foreach ($rev_arr as $arr_2) $new_array[$arr_2] = true; // do also for reverse
now you can check what you want to do based on
if ( isset($new_arr[ $YOUR_TEST_VARIABLE_HERE ]) ) { // match found
}

Categories