An array of MySQL results... - php

What am I doing wrong here?
I am attempting to return a json object and I can't seem to get past the array... I've built hundreds of regular array and returned them as a json object but I am having a hard time wrapping my head around this one.
$rows = array();
$post_array = array();
$i = 0;
$result = mysql_query(" SELECT * FROM forum_posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
while($row = mysql_fetch_assoc($result))
{
$post_array[$i] = $rows[ "id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate ];
$i++;
}

It looks like you mean to define an array for $post_array[$i] = .... Like this?
$post_array[$i] = array(
"id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate,
);
(Also, I just took the liberty to respace that a little for readability.)
To convert your array to JSON, pass it to json_encode().
Update: Oh, before you ask about it, I just noticed I added a comma out of habit after the last item in the array. It looks like it's out of place, but it's actually fine to have it there when defining arrays. It doesn't serve any special purpose, but it allows you to copy/paste/remove lines from the array without having to worry about whether or not to add/remove a trailing comma.
As an aside, you don't have to manually increment a numeric array index $i. If you just do this:
$post_array[] = array(...);
it will automatically assign the next available numeric index.

Do you mean do be doing something like this:
$post_array = array();
$i = 0;
$result = mysql_query(" SELECT * FROM forum_posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
while($row = mysql_fetch_assoc($result))
{
$post_array[$i] =array( "id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate );
$i++;
}
Then you can simply use json_encode to encode your array as json.
e.g.
echo json_encode($post_array);
You can't build an array the way you were with $rows[...], you need to use array. Also, instead of managing the ordinals for your array, you can just use array_push

Related

sql result as array of arrays

i'm trying to format the output of a sql query as an array of arrays, for using the gannti class graph tool on my sql data. I'm not very experienced(outside industrial plc's), and can't seem to find a solution to this particular problem despite lots of googeling.
The sql query i want to perform looks like this:
$query = "SELECT label, start, end from oppgaver ";
And the original array showed in the gannti class example is written like this:
$data = array();
data[] = array(
'label' => 'alarmkit',
'start' => '2013-08-01',
'end' => '2013-09-10'
);
$data[] = array(
'label' => 'Stekeovnskontroller',
'start' => '2013-08-22',
'end' => '2013-09-01'
);
$data[] = array(
'label' => 'Tull og fanteri',
'start' => '2013-09-02',
'end' => '2013-09-10'
);
And then you call the gantti to do it's thing:
$gantti = new Gantti($data, array(
'title' => 'Elektro',
'cellwidth' => 15,
'cellheight' => 35,
'today' => true
));
All works well, except for my unability to format the sql output to what i assume is an array of arrays so the gantti class can do its magic. I got it to show the first letter of each label in the sql database once, but that piece of mangled code i wrote should probably be forgotten :-)
Does anyone here have a idea about how to do this?
Update:
The last way i tried to get the data, by using msql_fetch_assoc.
Unfortunately i did not keep a record of the different approaches i made.
I've also tried several examples i found on using mysql_fetch_array, and mysql_fetch_row.
$query = "SELECT label, start, end from oppgaver ";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_assoc($result)) {
array_push($data, $row[0]);
}
Use $row to push in array in place of $row[0]
As given below
while ($row = mysql_fetch_assoc($result)) {
array_push($data, $row);
}

pushing and apending arrays into an associative array in php

How do I push arrays inside the "adjacencies" key value pair that should have an encapsulated array holding the "arrays" (ie. array(("nodeTo" => "$to"),("nodeTo" => "$to"))) without overwriting them and appending them similiar to "+=". also the push into the key "adjacencies" doesnt seem to pick up the value.
$node[] = array(
"adjacencies" => array(), //inside this array should go all the arrays seprated by commas.
"data" => array(
"color" => $color1,
"type" => $type1
);
// this push doesnt seem to detect the adjacencies value and doesnt really push the array inside of the container array. I also tried $node["adjacencies"][]=array("nodeTo" => "$to"); but it didnt work
$node["adjacencies"]=array("nodeTo" => "$to");
}
If you want multiple arrays within 'adjacencies', append them to the end of the array:
$node[0]['adjacencies'][] = array("nodeTo" => "$to");
Granted, you'll need to know which $node index to work with (if there are multiple nodes).
Edit:
After reading the comments, it looks like the OP's desired array structure is this:
$node = array(
'adjacencies' => array(),
'data' => array(
'color' => $color1,
'type' => $type1,
);
);
Thus, to append additional nodes to the adjacencies array, you can do this:
$node['adjacencies'][] = array('nodeTo' => "$to");
By the way you use $node in the second statement I think you meant:
$node = array(
not:
$node[] = array(
// ^^
Then you can push the array by doing:
$node['adjacencies'][] = array('nodeTo' => $to);

Find value of sibling key in php array

I have an array in PHP, here is a snippet:
$locations = array(
array(
"id" => 202,
"name" => "GXP Club - Fable"
),
array (
"id" => 204,
"name" => "GXP Club - Gray"
)
);
What I know (from a GET) is the ID (202). What I would like to display is
"Showing results for "
( where $locations[?][id] = $_GET['id'] { echo $locations[?][name] } )
- if you will pardon my use of pseudo code.
Not sure what function is best or if I need to loop over the whole array to find that. Thanks.
Edit: for further clarification. I need to learn the [name] given the [id]
foreach( $locations as $arr ) {
if($arr['id'] == $_GET['id']) {
echo $arr['name'];
break;
}
}
That should do the trick.
While looping over the array is the solution for the problem as described, it seems more optimal to change your array to be $id=>$name key-value pairs, instead of named key values if that's all the data in the array, e.g.:
$locations = array( '202' => 'GXP Club - Fable',
'204' => 'GXP Club - Gray',
)
Alternatively, if there's more data, I'd switch to a nested data structure, e.g.:
$locations = array( '202' => array( 'name' => 'GXP Club - Fable', 'prop2' =>$prop2, etc),
'204' => array( 'name' => 'GXP Club - Gray', 'prop2' =>$prop2, etc),
)
That makes it so you can access data via ID (e.g. $locations[$id]['name']), which seems to be what you'd generally be wanting to do.
You can use array_map function which applies your custom action to each element in given array.
array_map(
function($arr) { if ($arr['id'] == $_GET['id']) echo $arr['name']; },
$locations
);
Doing this with PHP's built-in array functions* avoids a foreach loop:
<?php
$locations = [["id"=>202, "name"=>"GXP Club - Fable"], ["id"=>204, "name"=>"GXP Club - Gray"]];
$col = array_search(array_column($locations, "id"), $_GET["id"]);
echo $locations[$col]["name"];
Or, using a different method:
<?php
$locations = [["id"=>202, "name"=>"GXP Club - Fable"], ["id"=>204, "name"=>"GXP Club - Gray"]];
$result = array_filter($locations, function($v){ return $v["id"] == $_GET["id"]; });
echo array_shift($result)["name"];
* Notably, array_column() was not available until PHP 5.5, released 10 months after this question was asked!

Replace array key integers with string

$string = "php, photoshop, css";
I'm producing an array from the comma separated values above using the str_getcsv() function:
$array = str_getcsv($string);
Result:
Array ( [0] => php [1] => photoshop [2] => css )
How can I replace the key integers with a string tag for all elements like seen below?
Array ( [tag] => php [tag] => photoshop [tag] => css )
Edit: if not possible what alternative can I apply? I need the array keys to be identical for a dynamic query with multiple OR clauses
e.g.
SELECT * FROM ('posts') WHERE 'tag' LIKE '%php% OR 'tag' LIKE '%photoshop% OR 'tag' LIKE '%css%'
I'm producing the query via a function that uses the array key as a column name and value as criteria.
That is not possible. You can have only one item per key. But in your example, the string "tag" would be the key of every item.
The other way arround would work. So having an array like this:
array('php' => 'tag', 'photoshop' => 'tag', 'css' => 'tag');
This might help you, if you want to save the "type" of each entry in an array. But as all the entries of your array seems to be from the same type, just forget about the "tag" and only store the values in a numeric array.
Or you can use a multidimensional array within the numeric array to save the type:
array(
0 => array( 'type' => 'tag', 'value' => 'php' ),
1 => array( 'type' => 'tag', 'value' => 'photoshop' ),
2 => array( 'type' => 'tag', 'value' => 'css' )
);
But still using just an numeric array should be fine if all the entries have the same type. I can even think of a last one:
array(
'tag' => array('php', 'photoshop', 'css')
);
But even if I repeat myself: Just use an ordinary array and name it something like $tag!
BTW: explode(', ', %string) is the more common function to split a string.
To build SQL statement you might do something like this:
// ... inside you build function
if(is_array($value)){
$sql .= "'".$key."' LIKE '%."implode("%' OR '".$key."' LIKE '%", $value)."%'";
} else {
$sql .= "'".$key."' LIKE '%".$value."%'";
}
This might look confusing but it's much cleaner than runnig into two foreach-loops building the query.
That won't work. Your array keys have to be unique, or subsequent additions will simply overwrite the previous key.
As the others said, keys have to be unique. Otherwise, which element should be returned if you access $arr['tag']? If you now say "all of them", then create a nested array:
$array = array();
$array['tag'] = str_getcsv($string);
The value $array['tag'] will be another array (the one you already have) with numerical keys. This makes, because you have a list of tags and lists can be represented as arrays too.
Understanding arrays is very important if you want to work with PHP, so I suggest to read the array manual.
Assuming you know the size of your array beforehand
$tags = array("tag1","tag2","tag3");
$data = array("php","photoshop","css");
$myarray = array();
for ($i=0; $i<count($data); $i++) {
$myarray[$i] = array($data[$i], $tags[$i]);
}
Then
echo $myarray[0][0] . ", " . $myarray[0][1];
Outputs:
php, tag1

PHP array : simple question about multidimensional array

i've got a SQL query which returns multiple rows, and i have :
$data = array(
"nom" => $row['nom'] ,
"prix" => $row['rapport'],
"average" => "$moyenne_ge"
);
which is perfect, but only if my query returns one row.
i tried that :
$data = array();
$data[$row['nom']]["nom"] = $row['nom'] ;
...
$data[$row['nom']]['average'] = "$moyenne_ge";
in order to have :
$data[brand1][nom] = brand1
$data[brand1][average] = 150$
$data[brand2][nom] = brand2
$data[brand2][average] = 20$
...
but when i do : json_encode($data)
i only have the latest JSON object instead of all JSON object from my request as if my array has only one brand instead of 10.
I guess i did something stupid somewhere.
Thanks for your help
I'd guess that your line:
$data = array();
Is initializing the array on each iteration of your loop. You aren't accumulating more than one row of data.
I guess something like this should work for you:
$resource = mysql_query("YOUR QUERY");
$results = array()
while($result = mysql_fetch_assoc($resource)) {
$results[$result['brand']] = array(
'nom' => $result['nom'],
'prix' => $result['rapport'],
'average' => $moyenne_ge
);
)
$results now contains all the rows from the query indexed by brand. Ask in comments if this wasn't what you're looking for.
If I am reading you right, you should just have to do something like this:
$data[] = array(
"nom" => $row['nom'] ,
"prix" => $row['rapport'],
"average" => "$moyenne_ge"
);
(notice the [])
This should append each array onto $data instead of overwriting the contents.

Categories