PHP - Array inside array dynamically - php

Previous, I have searched in Google. But I don't find what I want...
I want to add 2 array to an array. This is my code :
$labelCollection = array();
$labelArray1 = array("Staff ID", "Photo Profile");
$labelArray2 = array("Religion", "Postcode");
But, I want to make the result like this :
$labelCollection =
array('info_1' => array('Staff ID', 'Photo Profile'),
'info_2' => array('Religion', 'Postcode')
);

Try
<?php
$labelCollection = array();
$labelArray1 = array("Staff ID", "Photo Profile");
$labelArray2 = array("Religion", "Postcode");
$labelCollection = array('info_1' => $labelArray1 ,
'info_2' => $labelArray2
);

Related

php array ouput "null" values (values extracted from json file)

I've modify this code to get data from a json file instead of xml file (my old code)
<?php
$tracking_id = 'MyID'; //This is used to track the user doing the offer. can be email, clickid, subid.. etc
$userip = $_SERVER['REMOTE_ADDR']; //We need to get the users ip, so the rss feed can display the correct offers for their country.
$user_agent = $_SERVER['HTTP_USER_AGENT']; //lets collect their user agent to pass along.
$max_offers = 5; //max number of offers to display.
$str = file_get_contents('https://www.cpalead.com/dashboard/reports/campaign_json_load_offers.php?id=296213&geoip='.$userip.'&ua='.urlencode($user_agent).'&subid='.urlencode($tracking_id));
$json = json_decode($str, true);
$opOffer = array();
$offer_cnt = 0;
foreach($json['offers'] as $offeritem)
{
$opOffer[$offer_cnt] = array("title" => array($offeritem->title), "link" => array($offeritem->link));
$offer_cnt++;
};
if (0 == count($opOffer)):
echo 'Sorry there are no offers available for your region at this time.';
else:
echo json_encode($opOffer);
endif;
?>
and it's output like this:
[{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]},{"title":[null],"link":[null]}]
it should be like this:
[{"title":[{"What is Your Favorite Time for McDonald's?"}],"link":[{"https:\/\/filetrkr.com\/show.php?l=0&u=31802&id=5882&tracking_id=MyId"}]}]
Link to see json output: https://www.cpalead.com/dashboard/reports/campaign_json_load_offers.php?id=296213
For the line:
$opOffer[$offer_cnt] = array("title" => array($offeritem->title), "link" => array($offeritem->link));
Shouldn't it be either:
$opOffer[$offer_cnt] = array("title" => $offeritem->title, "link" => $offeritem->link);
or:
$opOffer[$offer_cnt] = array("title" => $offeritem['title'], "link" => $offeritem['link']);
Also, just after the line:
$json = json_decode($str, true);
Add this line and post the results:
echo "<p>JSON: <pre>".print_r($json,true)."</pre></p>";
That last bit to verify you are receiving the JSON you think you should be getting.
I just changed:
$opOffer[$offer_cnt] = array("title" => array($offeritem->title), "link" => array($offeritem->link));
to:
$opOffer[$offer_cnt] = array("title" => array($offeritem["title"]), "link" => array($offeritem["link"]));
And now give me what you want on the JSON:
[{"title":["Amplificador de Bater\u00eda"],"link":["http:\/\/gtrcking.com\/offer.php?id=744798&pub=296213&subid=MyID"]},{"title":["\u0645\u0628\u0627\u0631\u0627\u0629 \u0645\u0630\u0647\u0644\u0629!"],"link":["http:\/\/gtrcking.com\/offer.php?id=550635&pub=296213&subid=MyID"]},....
heres what you want. give that a go.
foreach($json['offers'] as $offeritem)
{
$opOffer[$offer_cnt] = array("title" => array($offeritem['title']), "link" => array($offeritem['link']));
$offer_cnt++;
if ($offer_cnt == $max_offers) break;
};

how to make simple quiz and button answer in telegram bot with php?

I want to make a simple question and the answer in multiple choice, the result what i want is like this picture : this is picture for desired the multiple choice button
but the result is not like what i desired this is the picture for result from my code : this is picture for not desired result
and this is the code that i have tried :
<?php
$token = "##################################";
$website = "https://api.telegram.org/bot".$token;
$array = array(array("1","2","3"));
$btn = array("keyboard" => $array,"hide_keyboard" => true,'selective' => true,);
$reply = json_encode($btn);
$url = $website."/sendmessage?chat_id=$chatIdtext=select : &reply_markup=".$reply;
file_get_contents($url);
?>
try this code, maybe the result like what you want.
<?php
$token = "######################################";
$website = "https://api.telegram.org/bot".$token;
$name1 = 'das';
$name2 = 'dsa';
$placeId1 = '1';
$placeId2 = '2';
$keyboard = [
'inline_keyboard' => [[['text' => $name1, 'callback_data' => $placeId1]], [['text' => $name2, 'callback_data' => $placeId2]]],
];
$reply = json_encode($keyboard);
$url = $website."/sendmessage?chat_id=130434215&text=select : &reply_markup=".$reply;
file_get_contents($url);
?>

Create multidimensional array from rows of data

I have a database with project entries. Each entry has a project title, datestamp, the user who entered it, and a comment. I am trying to format this data as JSON for reporting and charts.
I want an array for each project name, and inside that array an array for each entry.
I've tried several approaches but I haven't had much luck yet.
if ($result = $mysqli->query("SELECT * FROM project_entries"))
// WHERE WEEK(date) = WEEK(current_date) ORDER BY project_name
{
while ($row = mysqli_fetch_array($result)) {
$entry_array = array();
$row_array['project_name'] = $row['project_name'];
$comment = $row['comment'];
$entry = array (
'comment' => $comment,
);
$row_array['entries'] = $entry;
if ( !in_array($row['project_name'], $projects, false ))
{
array_push($projects, $row_array);
}
}
}
Outputs:
[
{
"project_name": "Logo Design",
"entries": {
"comment": "Worked on a thing"
}
},
{
"project_name": "Logo Design",
"entries": {
"comment": "Created some stuff"
}
},
While I want:
{
"project_name": "Logo Design",
"entries": {
"comment": "Worked on a thing",
"comment": "Created some stuff"
}
}
This should do the trick. You can use the project name as an array key. In order to prevent the string keys from showing up in your output array, you can use array_values to convert them to numeric keys.
$projects = array();
while ($row = mysqli_fetch_array($result)) {
$projects[$row['project_name']]['project_name'] = $row['project_name'];
$projects[$row['project_name']]['entries'][] = array('comment' => $row['comment']);
}
echo json_encode(array_values($projects));
What was going wrong with your previous code:
if ($result = $mysqli->query("SELECT * FROM project_entries")) {
while ($row = mysqli_fetch_array($result)) {
$entry_array = array(); // This does not appear to be used
// With each iteration of the while loop, you create a new array of
// project information (project name and entries array with one comment)
$row_array['project_name'] = $row['project_name'];
$comment = $row['comment'];
$entry = array ('comment' => $comment);
$row_array['entries'] = $entry;
// The $projects array is an array of arrays, but $row['project_name'] is
// a string. Checking if this string is in an array of arrays will always
// be false, so the array_push should always execute.
if (!in_array($row['project_name'], $projects, false )) {
// Adds the new project array to the projects array
array_push($projects, $row_array);
}
// This is not producing what you want because you are adding a new
// array to $row_array each time the loop runs
}
}
Why the code I suggested works:
$projects = array(); // Empty array to hold all the projects
while ($row = mysqli_fetch_array($result)) {
// Using the project name from the database as an array key in the array we are
// constructing keeps the projects unique in that array.
// The first time a new project name occurs, this will create a new sub-array
// within $projects with project_name => the new project name. This value will
// be overwritten on subsequent occurrences of the same project name.
$projects[$row['project_name']]['project_name'] = $row['project_name'];
// For each iteration, this will add a comment to the 'entries' array in the
// project array with the key $row['project_name'].
$projects[$row['project_name']]['entries'][] = array('comment' => $row['comment']);
// For example, with the first iteration of the array we create the following:
//
// $projects['Logo Design'][
// 'project_name' =>'Logo Design',
// 'entries' => [0 => ['comment' => 'Worked on a thing'] ] ]
//
// with the second iteration, the project name is overwritten (with same project name)
// and another comment array is added to the entries array
//
// $projects['Logo Design'][
// 'project_name' =>'Logo Design',
// 'entries' => [0 => ['comment' => 'Worked on a thing'],
// 1 => ['comment' => 'Created some stuff'] ] ]
}
// If you just did echo json_encode($projects), you would not get the format you want,
// because of the string keys. Try it without the array_values() to see what I mean.
echo json_encode(array_values($projects));
Maybe something like that?
Use project id to build target array.
while ($row = mysqli_fetch_array($result) {
if (!isset($projects[$row['id']]))
{
$projects[$row['id']] = [
'project_name' => $row['project_name'],
'entries' => [],
];
}
$projects[$row['id']]['entries'][] = [
'comment' => $row['comment'],
];
}

php - converting swithch to .csv file read method

Can someone please point me in the correct direction to convert my switch code from currently being listed like below to being drawn from a CSV file instead:
$video = (isset($_GET['video']) ? $_GET['video'] : null);
if($video) {
switch($video) {
case "apple":
$Heading ='Apple Heading';
$Videonum ='1';
$Content ='<h2>Apple Sub Heading</h2>
<p>Apple content</p>';
$SideContent ='Apple side content';
break;
I will end up with lots of cases and it'll be easier to manage from a .csv file - thank you
I think you need a two-dimensional array with the identifier ('apple', …) as the key for the inner arrays. By parsing a CSV-file you will get an array with multiple rows, but you need to search for the row, that contains the required data. Maybe you also can save PHP files containing the necessary data-arrays or even use a database (which is probably most common for such cases).
Target arrays as I would use it:
$data = array(
'apple' => array(
'heading' => 'Apple Heading',
'video_num' => 1,
'content' => '<h2>Apple Sub Heading</h2>
<p>Apple content</p>',
'side_content' => 'Apple side content',
),
/* more manufacturer sub-arrays */
);
In this first case you could access the whole data by just reading from the array:
if( !empty( $_GET['video'] ) && isset( $data[$_GET['video']] ) )
{
var_dump(
$data[$_GET['video']]['heading'],
$data[$_GET['video']]['content']
);
}
else
{
echo '<p class="error">No video specified or "' . $_GET['video'] . '" is not available.</p>';
}
FYI; Array as retrieved from a CSV-file:
$data = array(
1 => array(
'manufacturer' => 'Apple',
'heading' => 'Apple Heading',
'video_num' => 1,
'content' => '<h2>Apple Sub Heading</h2>
<p>Apple content</p>',
'side_content' => 'Apple side content',
),
/* more rows */
);
Read your csv file
$data = array();
$fp = fopen('manufacturer.csv', 'r');
while (!feof($fp)) {
$line = explode(';',fgets($fp));
$data[$line[0]]['heading'] = $line[1];
$data[$line[0]]['video'] = $line[2];
$data[$line[0]]['content'] = $line[3];
$data[$line[0]]['side'] = $line[4];
}
fclose($fp);
Your csv looks like
apple;Apple Heading;1;<h2>Apple Sub Heading</h2><p>Apple content</p>;Apple side content
microsoft;MS Heading;1;<h2>MS Sub Heading</h2><p>MS content</p>;MS side content
...
Then acces your content with the manufacturer name
if(isset($data[$_GET['video']] && !empty($_GET['video']))){
$Heading = $data[$_GET['video']]['heading'];
$Videonum = $data[$_GET['video']]['video'];
$Content = $data[$_GET['video']]['content'];
$SideContent = $data[$_GET['video']]['side'];
}

Extracting and grouping database data to an array

I have a database field called "servers"
This field has a link in each row, this field content:
> http://www.rapidshare.com/download1
> http://www.rapidshare.com/download2
> http://www.rapidshare.com/download3
> http://www.megaupload.com/download1
> http://www.megaupload.com/download2
> http://www.megaupload.com/download3
> http://www.fileserve.com/download1
> http://www.fileserve.com/download2
> http://www.fileserve.com/download3
I want to create an array with all the server names, and create more array with links inside.
That's how it should be:
$servers = array(
'rapidshare' => array(
'link1' => 'http://www.rapidshare.com/download1',
'link2' => 'http://www.rapidshare.com/download2',
'link3' => 'http://www.rapidshare.com/download3'),
'megaupload' => array(
'link1' => 'http://www.megaupload.com/download1',
'link2' => 'http://www.megaupload.com/download2',
'link3' => 'http://www.megaupload.com/download3'),
'fileserve' => array(
'link1' => 'http://www.megaupload.com/download1',
'link2' => 'http://www.megaupload.com/download2',
'link3' => 'http://www.megaupload.com/download3')
);
This will do the trick: (make sure that domain is actually showing up in $domain variable though because it might be $matches[1]... I can't remember)
$newStructure = array();
foreach($links as $link) {
preg_match("/www\.([^\.])\.com/",$link,$matches);
$domain = $matches[0];
$currentLength = count($newStructure[$domain]);
if($currentLength) {
$newStructure[$domain]['link'.($currentLength+1)] = $link;
} else {
$newStructure[$domain] = array('link1'=>$link);
}
}
$server = array(
'http://www.rapidshare.com/download1',
'http://www.rapidshare.com/download2',
'http://www.rapidshare.com/download3',
'http://www.megaupload.com/download1',
'http://www.megaupload.com/download2',
'http://www.megaupload.com/download3',
'http://www.fileserve.com/download1',
'http://www.fileserve.com/download2',
'http://www.fileserve.com/download3'
);
$match = array();
$myarray = array();
foreach($server as $v) {
// grab server name
preg_match('/\.(.+)\./', $v, $match);
$serverName = $match[1];
// initialize new array if its the first link of that particular server
if (!isset($myarray[$serverName])) {
$myarray[$serverName] = array();
}
// count server array to check how many links are there, and make next link key
$linkKey = 'link' . (count($myarray[$serverName]) + 1);
// store value
$myarray[$serverName][$linkKey] = $v;
}
print_r($myarray);
Hey maybe this will help you. But i dont see the purpose of those names of the keys (link1,link2 etc..). This wont work on pagination thou.

Categories