Foreach loop in an Array - php

I am using fullcalendar (JSON) and want to use a foreach loop in a multidimensional array. What I've got is this:
echo json_encode(array(
array(
'id' => 111,
'title' => $arr['new'][0] . ' new',
'start' => $arr['booking_date'][0],
'url' => "bookings/new/1",
'color' => '#F7F8E0',
'textColor' => 'black'
),
array(
'id' => 111,
'title' => $arr['completed'][0] . ' completed',
'start' => $arr['booking_date'][0],
'url' => "bookings/completed/1",
'color' => '#D8D8D8',
'textColor' => 'black'
),
array(
'id' => 111,
'title' => $arr['accepted'][0] . ' accepted',
'start' => $arr['booking_date'][0],
'url' => "bookings/accepted/1",
'color' => '#E0ECF8',
'textColor' => 'black'
),
));
Now i have to input every array manually, but how can I use foreach to do that for me?
I've tried something like this, but it didn't work.
echo json_encode(array(
foreach($arr as $row) {
array(
'id' => 111,
'title' => $arr['new'][0] . ' new',
'start' => $arr['booking_date'][0],
'url' => "bookings/new/1",
'color' => '#F7F8E0',
'textColor' => 'black'
),
}

I guess you are looking for this:
<?php
$array = array();
$arr = array(
array(
'new' => array("Title 1"),
'booking_date' => array("Booking date 1")
),
array(
'new' => array("Title 2"),
'booking_date' => array("Booking date 2")
)
);
foreach($arr as $row) {
array_push($array, array(
'id' => 111,
'title' => $row['new'][0] . ' new',
'start' => $row['booking_date'][0],
'url' => "bookings/new/1",
'color' => '#F7F8E0',
'textColor' => 'black'
));
}
echo json_encode($array);

Related

Loop Through Nested JSON Response PHP

I'm trying to loop through and return data ('rank' from 'rank_details') from a returned JSON response.
Here is a snippet of the JSON response (what I'm getting from: $array = json_decode($apiResponse); )
(object) array(
'obj' =>
array (
0 =>
(object) array(
'name' => 'I\'m a HellRazor (feat. Crucifix)',
'id' => 13859011,
'data' =>
array (
0 =>
(object) array(
'timestp' => '2019-10-27T00:00:00.000Z',
'score' => 1.9610844011276853,
'rank_details' =>
array (
0 =>
(object) array(
'rank' => 191,
'country' => 'RU',
'score' => 1.9610844011276853,
'genre' => 'Country',
),
),
),
1 =>
(object) array(
'timestp' => '2019-12-04T00:00:00.000Z',
'score' => 14.70808550760029,
'rank_details' =>
array (
0 =>
(object) array(
'rank' => 9,
'country' => 'CH',
'score' => 14.70808550760029,
'genre' => 'Country',
),
),
),
2 =>
(object) array(
'timestp' => '2020-03-18T00:00:00.000Z',
'score' => 13.299189761918104,
'rank_details' =>
array (
0 =>
(object) array(
'rank' => 5,
'country' => 'RU',
'score' => 13.299189761918104,
'genre' => 'Country',
),
),
),
3 =>
(object) array(
'timestp' => '2020-07-12T00:00:00.000Z',
'score' => 19.02841337415393,
'rank_details' =>
array (
0 =>
(object) array(
'rank' => 77,
'country' => 'DE',
'score' => 19.02841337415393,
'genre' => 'Country',
),
),
),
4 =>
(object) array(
'timestp' => '2020-10-02T00:00:00.000Z',
'score' => 2.631257456412845,
'rank_details' =>
array (
0 =>
(object) array(
'rank' => 154,
'country' => 'RU',
'score' => 2.631257456412845,
'genre' => 'Country',
),
),
),
5 =>
(object) array(
'timestp' => '2020-10-03T00:00:00.000Z',
'score' => 1.896575572629275,
'rank_details' =>
array (
0 =>
(object) array(
'rank' => 195,
'country' => 'RU',
'score' => 1.896575572629275,
'genre' => 'Country',
),
),
),
),
),.....
Here is a snippet of my code:
$apiResponse = curl_exec($cc);
$array = json_decode($apiResponse);
foreach ($array as $key => $arrays) { // This will search in the 2 jsons
foreach($arrays as $key => $value) {
echo "\n Record ID: " . $value->id;
echo "\n Record Name: " . $value->name;
echo "\n Record Rank: " . $value->obj->data->rank_details->rank;
echo "\n";
}
}
Record Name and ID come over fine, but anything not in the "top level" isn't coming over. Any help is GREATLY appreciated.
You have to index into the data and rank_details arrays even if there's only one entry.
This worked for me:
echo "\n Record Rank: " . $value->data[0]->rank_details[0]->rank;

Add values from multidimensional array to another array

Hello good morning wherever you are :D, i have a lil problem, i have this code of arrays
$arrayToView is the info of every single user that i want.
$tagsArray are only tags that use every user but i need to merge all the info something like the last array...
$arrayToView = array(
'IVOFACUNDO' = array(
'mails' => 3,
'contacts' => 34,
'blocked' => 23
),
'ESRAYCU' = array(
'mails' => 23,
'contacts' => 124,
'blocked' => 44
)
)
And i have another one like this
$tagsArray= array(
'IVOFACUNDO' = array(
'14' => array(
'id' => 14,
'name' => 'php',
'value' => 1
),
'15' => array(
'id' => 15,
'name' => 'javascript',
'value' => 1
)
),
'ESRAYCU' = array(
'1' => array(
'id' => 1,
'name' => 'python',
'value' => 1
),
'15'=> array(
'id' => 15,
'name' => 'javascript',
'value' => 1
)
)
)
so the question is how i can merge both arrays obviously respectively with the same admin something like this
$arrayToView = array(
'IVOFACUNDO' = array(
'mails' => 3,
'contacts' => 34,
'blocked' => 23,
'tags' => array(
'14' => array(
'id' => 14,
'name' => 'php',
'value' => 1
),
'15' => array(
'id' => 15,
'name' => 'javascript',
'value' => 1
)
)
),
'ESRAYCU' = array(
'mails' => 23,
'contacts' => 124,
'blocked' => 44,
'tags' => array(
'1' => array(
'id' => 1,
'name' => 'python',
'value' => 1
),
'15'=> array(
'id' => 15,
'name' => 'javascript',
'value' => 1
)
)
)
)
The key 'tags' need to be created in the merge of every iteration to add and get one array with all the values, how i can do this?
You can try this snippet.
foreach($arrayToView as $key => $arr){
if(array_key_exists($key, $tagsArray)){
$arrayToView[$key]['tags'] = $tagsArray[$key];
}
}
echo '<pre>';print_r($arrayToView);echo '</pre>';
Use php inbuilt function
$result_Arr = array_merge_recursive($arrayToView,$tagsArray);
<?php
$arrayToView = array(
'IVOFACUNDO' => array(
'mails' => 3,
'contacts' => 34,
'blocked' => 23
),
'ESRAYCU' => array(
'mails' => 23,
'contacts' => 124,
'blocked' => 44
)
);
$tagsArray= array(
'IVOFACUNDO' => array(
'14' => array(
'id' => 14,
'name' => 'php',
'value' => 1
),
'15' => array(
'id' => 15,
'name' => 'javascript',
'value' => 1
)
),
'ESRAYCU' => array(
'1' => array(
'id' => 1,
'name' => 'python',
'value' => 1
),
'15'=> array(
'id' => 15,
'name' => 'javascript',
'value' => 1
)
)
);
foreach($arrayToView as $key => $value){
if(isset($tagsArray[$key])){
$arrayToView[$key]['tags'] = array();
foreach($tagsArray[$key] as $key2 => $value2){
$arrayToView[$key]['tags'][$key2] = $tagsArray[$key][$key2];
}
}
}
echo'<pre>';
print_r($arrayToView);
echo'</pre>';
?>

php reformat nested array

I have a stored unlimited nested levels array with unwanted extra data.
$arr = array(
array(
'name' => 'item1',
'level' => 0,
'extra_key' => 'some_data',
'children' => array(
'name' => 'sub-item1',
'level' => 1,
'extra_key' => 'some_data',
'children' => array(
'name' => 'sub-sub-item1',
'level' => 2,
'extra_key' => 'some_data',
'children' => array()
),
array(
'name' => 'sub-sub2-item1',
'level' => 2,
'extra_key' => 'some_data',
'children' => array()
),
)
),
array(
'name' => 'item2',
'level' => 0,
'extra_key' => 'some_data',
'children' => array(
'name' => 'sub-item2',
'level' => 2,
'extra_key' => 'some_data',
'children' => array(
'name' => 'sub-sub-item2',
'level' => 2,
'extra_key' => 'some_data',
'children' => array()
),
array(
'name' => 'sub-sub2-item2',
'level' => 2,
'extra_key' => 'some_data',
'children' => array()
),
)
),
array(
'name' => 'item3',
'level' => 0,
'extra_key' => 'some_data',
'children' => array(
'name' => 'sub-item3',
'level' => 1,
'extra_key' => 'some_data',
'children' => array(
'name' => 'sub-sub-item3',
'level' => 2,
'extra_key' => 'some_data',
'children' => array()
),
array(
'name' => 'sub-sub2-item3',
'level' => 2,
'extra_key' => 'some_data',
'children' => array()
),
)
),
);
Expected output array:
$arr = array(
array(
'name' => 'item1',
'nodes' => array(
'name' => 'sub-item1',
'nodes' => array(
'name' => 'sub-sub-item1',
'nodes' => array()
),
array(
'name' => 'sub-sub2-item1',
'nodes' => array()
),
)
),
array(
'name' => 'item2',
'nodes' => array(
'name' => 'sub-item2',
'nodes' => array(
'name' => 'sub-sub-item2',
'nodes' => array()
),
array(
'name' => 'sub-sub2-item2',
'nodes' => array()
),
)
),
array(
'name' => 'item3',
'nodes' => array(
'name' => 'sub-item3',
'nodes' => array(
'name' => 'sub-sub-item3',
'nodes' => array()
),
array(
'name' => 'sub-sub2-item3',
'nodes' => array()
),
)
)
);
I want to remove unwanted keys like level , extra_key from all levels and i want also to change the name of the key children to nodes then reproduce the same array with the same structure with the new format.
How can i achieve that?
I tried to do it by recursive function but i failed to reproduce the same structrue
Your structure doesn't make sense, probably because of that you was unable to write recursive function. If it is possible to change structure, I would suggest this one (with reformat function implementation):
<?php
$actual = array(
array(
'name' => 'item1',
'level' => 0,
'extra_key' => 'some_data',
'children' => array(
array(
'name' => 'sub-item1',
'level' => 1,
'extra_key' => 'some_data',
'children' => array(
array(
'name' => 'sub-sub-item1',
'level' => 2,
'extra_key' => 'some_data',
'children' => array()
),
array(
'name' => 'sub-sub2-item1',
'level' => 2,
'extra_key' => 'some_data',
'children' => array()
),
)
),
)
),
);
$expected = array(
array(
'name' => 'item1',
'nodes' => array(
array(
'name' => 'sub-item1',
'nodes' => array(
array(
'name' => 'sub-sub-item1',
'nodes' => array()
),
array(
'name' => 'sub-sub2-item1',
'nodes' => array()
),
),
),
)
),
);
function change_array($original)
{
return array_map('change_node', $original);
}
function change_node($node)
{
return [
'name' => $node['name'],
'nodes' => array_map('change_node', $node['children']),
];
}
var_dump($expected === change_array($actual));
This function will do what you want recursively.
You can add extra excluded and/or renamed indices if required;
function parseArray($array): array
{
// The resulting array
$result = [];
// Indices you want renamed [`from` => `to`]
$renameIndices = ['children' => 'nodes'];
// Indices you want excluded [`1`, `2`]
$excludedIndices = ['level', 'extra_key'];
foreach ($array as $idx => $content)
{
// If excluded, continue (skip) node.
if (in_array($idx, $excludedIndices, true))
{
continue;
}
// Setting the resulting (new) index.
$resultIdx = $idx;
// Check if this index should be renamed
if (array_key_exists($idx, $renameIndices))
{
// If index should be renamed, apply new name
$resultIdx = $renameIndices[$idx];
}
// If this content block is an array. Parse it.
if (is_array($content))
{
$content = parseArray($content);
}
// Save content to resulting array.
$result[$resultIdx] = $content;
}
return $result;
}

Printing all array results in a themable way using PHP?

I want to print all results of the taxonomy_vocabulary_11 array (this is a Drupal 7 site).
If I use <?php print render($content['taxonomy_vocabulary_11'][0]['#title']); ?> I get only one result.
I´ve usuccessfully tried
<?php foreach ($content->taxonomy_vocabulary_11 as $key => $value): $terms = $value['#title']; ?>
<?php print $terms; ?>
<?php endforeach?>
I get this error: Notice: Trying to get property of non-object
Now, this is the output I get using devel module (dpm($node);)
(object) array(
'vid' => '5178',
'uid' => '1',
'title' => 'PROYECTO',
'log' => '',
'status' => '1',
'comment' => '2',
'promote' => '0',
'sticky' => '0',
'nid' => '155',
'type' => 'jornadas',
'language' => 'und',
'created' => '1095048000',
'changed' => '1360589684',
'tnid' => '0',
'translate' => '0',
'revision_timestamp' => '1360589684',
'revision_uid' => '1',
'taxonomy_vocabulary_4' => array(),
'taxonomy_vocabulary_6' => array(
'und' => array(
array(
'tid' => '33',
'taxonomy_term' => (object) array(
'tid' => '33',
'vid' => '6',
'name' => 'Jornadas Gratuitas',
'description' => '',
'format' => NULL,
'weight' => '0',
'vocabulary_machine_name' => 'vocabulary_6',
),
),
),
),
'taxonomy_vocabulary_7' => array(
'und' => array(
array(
'tid' => '40',
'taxonomy_term' => (object) array(
'tid' => '40',
'vid' => '7',
'name' => 'Para PH',
'description' => '',
'format' => NULL,
'weight' => '-10',
'vocabulary_machine_name' => 'vocabulary_7',
),
),
),
),
'taxonomy_vocabulary_11' => array(
'und' => array(
array(
'tid' => '262',
'taxonomy_term' => (object) array(
'tid' => '262',
'vid' => '11',
'name' => 'colegios',
'description' => '',
'format' => NULL,
'weight' => '0',
'vocabulary_machine_name' => 'vocabulary_11',
),
),
array(
'tid' => '543',
'taxonomy_term' => (object) array(
'tid' => '543',
'vid' => '11',
'name' => 'derecho',
'description' => '',
'format' => NULL,
'weight' => '0',
'vocabulary_machine_name' => 'vocabulary_11',
),
),
),
),
'body' => array(
'und' => array(
array(
'value' => "
I´ve also tried <?php print render($content['taxonomy_vocabulary_11']); ?> to treat the taxonomy as any other field, but it won´t print anything.
Note: If I go and do print $content['taxonomy_vocabulary_11']; it just print the word array.
What´s wrong in my approach?
Try:
foreach ($content['taxonomy_vocabulary_11'] as $tv11) {
print render($tv11['#title']);
}
I dont use drupal but this should work if i understood how the $content['taxonomy_vocabulary_11'] array is structured.
Just in case anyone needs it:
<?php
$vid = 11; //vocabulary id
$nid = $node->nid; //it looks for the current loaded node
$query = "SELECT tid, name
FROM (
SELECT td.tid AS tid, name
FROM taxonomy_term_data AS td
JOIN taxonomy_index AS tn
ON td.tid = tn.tid
JOIN node AS n
ON n.nid = tn.nid
WHERE td.vid = ". $vid ."
AND n.status = 1
AND n.nid = ".$nid."
GROUP BY td.tid
) AS t
ORDER BY name ASC";
$result = db_query($query);
foreach($result as $term) {
echo l($term->name, "taxonomy/term/$term->tid") . ', ';
}
?>

PHP: Help with Sorting Array

How can I sort an associative array by a weight AND type?
Input
array(
'a' => array( 'type' => 't1', 'weight' => 1, 'text' => 'text1' ),
'b' => array( 'type' => 't1', 'weight' => 3, 'text' => 'text2' ),
'c' => array( 'type' => 't2', 'weight' => 5, 'text' => 'text3' ),
'd' => array( 'type' => 't1', 'weight' => 2, 'text' => 'text4' ),
'e' => array( 'type' => 't2', 'weight' => 4, 'text' => 'text5' ),
'f' => array( 'type' => 't2', 'weight' => 4, 'text' => 'text6' )
);
Desired Output
array(
'a' => array( 'type' => 't1', 'weight' => 1, 'text' => 'text1' ),
'd' => array( 'type' => 't1', 'weight' => 2, 'text' => 'text4' ),
'b' => array( 'type' => 't1', 'weight' => 3, 'text' => 'text2' ),
'e' => array( 'type' => 't2', 'weight' => 1, 'text' => 'text5' ),
'f' => array( 'type' => 't2', 'weight' => 1, 'text' => 'text6' ),
'c' => array( 'type' => 't2', 'weight' => 5, 'text' => 'text3' )
);
Type "t2" must appear at end of array, all other types at start.
Weight must be sorted after type.
I am using uasort with a custom compare function, but am struggling. Here is what I have, but it doesn't work:
function my_comparer($a, $b) {
return ( $a['type'] !== 't2' && $b['type'] === 't2' )
? -1
: $a['weight'] - $b['weight'];
}
Your function doesn't take account of ($a['type']=='t2')
function my_comparer($a, $b) {
if ( ($a['type']==='t2') && ($b['type']!=='t2')) return -1;
if ( ($b['type']==='t2') && ($a['type']!=='t2')) return 1;
return ($a['weight'] - $b['weight']);
}
Try this:
function my_comparer($a, $b) {
if( $a['type'] == $b['type'] ){
return $a['weight'] - $b['weight'];
}else{
if( $a['type'] > $b['type'] ) return 1;
else return -1;
}
}
(warning, this is untested)
Simpler way would be array_multisort
$data = array(
'a' => array( 'type' => 't1', 'weight' => 1, 'text' => 'text1' ),
'b' => array( 'type' => 't1', 'weight' => 3, 'text' => 'text2' ),
'c' => array( 'type' => 't2', 'weight' => 5, 'text' => 'text3' ),
'd' => array( 'type' => 't1', 'weight' => 2, 'text' => 'text4' ),
'e' => array( 'type' => 't2', 'weight' => 4, 'text' => 'text5' ),
'f' => array( 'type' => 't2', 'weight' => 4, 'text' => 'text6' )
);
// Obtain a list of columns
foreach ($data as $key => $row) {
$type[$key] = $row['type'];
$weight[$key] = $row['weight'];
}
array_multisort($type, SORT_ASC, $weight, SORT_ASC, $data);
Plus this works if you add any number of types you want sorted in the same way.
Helper function:
function arrayColumnSort(&$array, $directions) {
// collect columns
$columnNames = array_keys($directions);
$columns = array();
foreach ($array as $row) {
foreach ($columnNames as $columnName) {
if (!isset($columns[$columnName])) {
$columns[$columnName] = array();
}
$columns[$columnName][] = isset($row[$columnName]) ? $row[$columnName] : null;
}
}
// build array_multisort params
$params = array();
foreach ($directions as $columnName => $direction) {
$params = array_merge(
$params,
array($columns[$columnName]),
is_array($direction) ? $direction : array($direction)
);
}
$params[] =& $array;
// sort
call_user_func_array('array_multisort', $params);
}
Call:
arrayColumnSort($data, array(
'type' => SORT_ASC,
'weight' => SORT_ASC,
));

Categories