PHP echo array value after while loop - php

How can I echo out value after the while loop. If I do the echo in below code its says Undefined index.
$sql_cast = "SELECT *
FROM
title_cast
INNER JOIN title ON (title_cast.id_title = title.id)
INNER JOIN `cast` ON (title_cast.id_cast = `cast`.id)
WHERE
title_cast.id_title = '1'";
$result_cast = mysql_query($sql_cast) or die('log error with' .mysql_error());
$cast = array();
while ($row = mysql_fetch_assoc($result_cast)) {
$id = $row['id'];
$name = $row['name'];
$img = $row['photo_localurl'];
$poster = str_replace("./", "lib/", $img);
$cast[] = array('id' => $id, 'name' => $name, 'img' => $poster);
//$cast[] = $row;
}
//var_dump($cast);
echo $cast['id'] . " " . $cast['name'] . " " . $cast['poster']."<br />";

Within the while loop, you set the cast array content using $cast[] syntax. This will create a numerical index, starting at 0, then 1 and so on, so you're creating an array that looks like this:
$cast = array(
0 => array('id' => $id, 'name' => $name, 'img' => $poster),
1 => array('id' => $id, 'name' => $name, 'img' => $poster)
);
You need to include the numerical key of the array that you want to echo. For example, if you want to echo the first row:
echo $cast[0]['id']; // Echo the id of the first result
If you want to echo ALL of the rows, use foreach:
foreach($cast as $row) {
echo $row['id'];
}

Maybe you should do:
$cast = array('id' => $id, 'name' => $name, 'img' => $poster);
//$cast[] = $row;
}
//var_dump($cast);
echo $cast['id'] . " " . $cast['name'] . " " . $cast['poster']."<br />";
because if you use $cast[], it will append the new array to your array..

That's because you are pushing a new array in $cast at each index..
So you should echo like this..
$i = 0;
while ($row = mysql_fetch_assoc($result_cast)) {
$id = $row['id'];
$name = $row['name'];
$img = $row['photo_localurl'];
$poster = str_replace("./", "lib/", $img);
$cast[] = array('id' => $id, 'name' => $name, 'img' => $poster);
//$cast[] = $row;
//var_dump($cast);
echo $cast[$i]['id'] . " " . $cast[$i]['name'] . " " . $cast[$i]['poster']."<br />";
$i++;
}

Try this:
<?php
while ($row = mysql_fetch_assoc($result_cast)) {
$id = $row['id'];
$name = $row['name'];
$img = $row['photo_localurl'];
$poster = str_replace("./", "lib/", $img);
$cast[] = array('id' => $id, 'name' => $name, 'img' => $poster);
}
foreach($cast as $rows) {
echo $rows['id']." ".$rows['name']." ".$rows['img']."<br />";
}
?>

print_r($cast[0]); or you can use $cast[0]['id'] ;

There are two problems with your code, First is that $cast[] is a two-dimensional array so it contains arrays at each of its index, so you must use
$cast[$i]['id']
Where i will be the counter variable that will iterate through all the indexes. Secondly change
$cast['poster']
to
$cast['img']
Hope this helps.

Related

How to dynamically fill key and value in an associative array using for loop in PHP

$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
Here i added
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4"
using $str Dynamically with the help of for loop because it is dynamic not fixed.
I want to make this array like the below, so it can work and print correct output - It's my desired output(I want this array like this to be working)
array(
"data"=>array(
"userid"=>"$row->uid",
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"acc_id"=>"$acc_id",
"tloop"=>"$timeloopc"
),
"next"=>"$next"
);
Output is -
But array taking the value of $str as string and when i print thisit shows output -
Array (
[data] => Array (
[user1] => 1
[0] => "value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"value5"=>"$row->field5"
[user2] => 2
[fi] => 3
)
[next] => 4
)
The Above output is issue... Here array processing some key and value but not processing $str value... it's taking it as sting.
It's now processing the $str values as string from "value1" and "field1"..to..4
Help me to dynamically fill key and value in an associative array using for loop.
In the array "value1 and field1" - here numbers are dynamic - "value2" and "field2"...
When i am making array dynamic, it's not working like array. If i make it static it works fine.
So please help me to make $str value from string to array value(object)...
Here is complete code -
<?php
$ct = 4;
$str = '';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= '"value';
$cuntc = $cunt.'"';
$rw = '"$row';
$fild= "field";
$cp = $valu.$cuntc."=>".$rw."->".$fild.$cuntc;
$str .= $cp . ',';
}
//trim the , from last value
$str = rtrim($str, ",");
$main= array("data"=>array("userid"=>"1","$str","acc_id"=>"10","fi"=>"3"),"next"=>"4");
print_r($main);
?>
I don't know what exactly you want.
There is a code, which build array you'd like to have:
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$ct = 4;
$subArray = array();
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$resultArray['data'][$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
echo "<pre>";
var_dump($resultArray);
echo "</pre>";
But if you don't need restricted key ordering, you can use something like this (it's rebuild $main array):
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$fields = array();
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$fields[$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
foreach ($fields as $key => $value) {
$main['data'][$key] = $value;
}
And there is solution with functions:
function generateFieldArray($keyName, $obj, $field, $rowCount)
{
$resultArray = array();
for($count=1; $count<=$rowCount; $count++)
{
$resultArray[$keyName . $count] = '$' . $obj . '->' . $field .$count;
}
return $resultArray;
}
function buildMainArray($inputArray, $keyName, $obj, $field, $rowCount)
{
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$inputArray['data'][$key] = $value;
}
return $inputArray;
}
function buildMainArray2($inputArray, $keyName, $obj, $field, $rowCount)
{
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$resultArray['data'][$key] = $value;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
return $resultArray;
}
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$result = buildMainArray($main, 'value', 'row', 'field', 4);
// or
$result = buildMainArray2($main, 'value', 'row', 'field', 4);

I have a question about JSON PHP Multi Values

I want to select the database more values (I already did) and be converted to JSON
I tried all
php
$a = $_GET['name'];
header('Content-Type: application/json');
echo '{"results":[';
$selectSearch = "SELECT * from `users` WHERE `name` LIKE '".$a["term"]."%'";
$rezultatul = $db->query($selectSearch);
if ($rezultatul->num_rows > 0) {
while($row = $rezultatul->fetch_assoc()) {
$name = $row["name"];
$arr = array('id' => $row["id"], 'text' => $row["name"], 'level' => $row["Level"]);
echo json_encode($arr);
}
}
echo ']}';
And he looks like this:
{"results":[{"id":"1","text":"Pompiliu","level":"7"}
{"id":"11","text":"Pompiliu1","level":"100"}]}
But between the two must be like that
{"id":"1","text":"Pompiliu","level":"7"},
{"id":"11","text":"Pompiliu1","level":"100"}
And when there will be 3 results
{"id":"1","text":"Pompiliu","level":"7"},
{"id":"11","text":"Pompiliu1","level":"100"},
{"id":"12","text":"Pompiliu2","level":"100"}
Add to the array with [] and then json_encode.
Don't try and build json strings on your own.
if ($rezultatul->num_rows > 0) {
while($row = $rezultatul->fetch_assoc()) {
$name = $row["name"];
$arr[] = array('id' => $row["id"], 'text' => $row["name"], 'level' => $row["Level"]);
}
}
echo json_encode(["results" => $arr]);

Get Specific Value From Json array in PHP

I'm Try To Access Some specific Value From Return JSON
Real Value is 79#45#597#10#10#10000#M
$retframe = str_ireplace('#',',', $stframe);
echo json_encode(array( 'Value' => $retframe));
///Output Response Back is
{"Value":"79,45,597,10,10,10000,M"}
I Want to Get Only Value of 79,597,10
If you need the 1st, 3rd and 5th number of $stframe
$stframe = '79#45#597#10#10#10000#M';
list($p1,$p2,$p3,$p4,$p5,$p6,$p7) = explode('#',$stframe);
$retframe = $p1 . ',' . $p3 . ',' . $p5;
echo json_encode(array( 'Value' => $retframe));
if you want to get 79,597,10 values statically than you will do it like this way.
$retframe = str_ireplace('#',',', $stframe);//$retframe = '79,45,597,10,10,10000,M';
$rs = explode(",",$retframe);
$array[] = $rs[0];
$array[] = $rs[2];
$array[] = $rs[3];
$array1= implode(",", $array);
echo json_encode(array( 'Value' => $array1));
and you will get result like this : {"Value":"79,597,10"}

Put a lang function inside of a php string

Trying to do a translation of my MySQL DB to PHP.
Here's the code:
$sql = "SELECT Name, Price FROM utf WHERE Name LIKE 'K%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class=\"CSSTableGenerator style=\"width:600px;height:150px;\"><table><tr><th>Name</th><th>Price</th></tr></div>";
// output data of each row
while($row = $result->fetch_assoc()) {
$name = str_replace('K', 'Karambit', $row['Name']);
echo "<tr><td>".$name."</td><td>".$row["Price"]." ".$row["Trend"]."</td></tr>";
}
echo "</table>";
So Select, Filter by signature character, and then translate.
Now, I have a lang.php file which has the translations.
Here it is:
<?php
function lang($phrase){
static $lang = array(
'ba' => 'Bayonet',
'ka' => 'Karambit'
);
return $lang[$phrase];
}
?>
How do I put it in this line:
$name = str_replace('K', 'Karambit', $row['Name']);
and replace 'ka' => 'Karambit' with 'Karambit'?
Non of these have worked:
//attempt 1
$name = str_replace('K', 'lang('ka');', $row['Name']);
//attempt 2
$name = str_replace('K', '$lang('ka');', $row['Name']);
//attempt 3
$word = echo lang('ka');
$name = str_replace('K', '$word', $row['Name']);
Don't put function calls in quotes, just use:
$name = str_replace('K', lang('ka'), $row['Name']);
//^^^^^^^^^^ See here
Also to give you another option:
You can store your search => replace values into an array like this:
$searchReplace = [
"ba" => "Bayonet",
"ka" => "Karambit",
];
And then you can simply use strtr() to replace it, e.g.
$name = strtr($row['Name'], $searchReplace);

How to return the value of the array in this code?

I'm newbie here., I want to get the array value that I set in an array.
I have this simple code here. Hope someone could help me..What is the correct way to set this one?
<?php
include('datacon.php');
//$id = $_GET['id'];
$list = mysql_query("SELECT PatientID,Fname,Mname,Lname
FROM tbl_PatientInfo WHERE PatientID = '1' ");
$result = array();
foreach( mysql_fetch_array($list) as $row){
$result[] = array(
'id' => $row['PatientID'],
'fname' => $row['Fname'],
'mname' => $row['Mname'],
'lname' => $row['Lname']
);
}
echo json_encode($result);
?>
When i try this code. It said an error:
Warning: Illegal string offset 'PatientID' on line 15
This line is incorrect:
foreach( mysql_fetch_array($list) as $row){
This is retrieving just one row, and then iterating over the columns in that row. The columns are just strings, not arrays, which is why you get illegal string offset errors.
You want to retrieve each row, you do that with:
while ($row = mysql_fetch_array($list)) {
You are not getting an associative array that's why it is invalid to use:
mysql_fetch_assoc($list) as $row
rather than
mysql_fetch_array($list) as $row
Use mysql_fetch_assoc as don't need numeric indexes in your output, so mysql_fetch_array is a bit of an overhead.
$result = array();
while( ($row = mysql_fetch_assoc( $list ) ) !== false ) {
$result[] = array(
'id' => $row['PatientID'],
'fname' => $row['Fname'],
'mname' => $row['Mname'],
'lname' => $row['Lname']
);
}
fetch_array() : $row[0], $row[1], etc...
fetch_assoc() : $row['PatientID'], $row['Fname'], etc...
fetch_object() : $row->PatientID, $row->Fname, etc...
<?php
include('datacon.php');
//$id = $_GET['id'];
$list = mysql_query("SELECT PatientID,Fname,Mname,Lname
FROM tbl_PatientInfo WHERE PatientID = '1' ");
$result = array();
$i=0;
while( $row=mysql_fetch_array($list)){
$result[$i]['id'] = $row['PatientID'];
$result[$i]['fname'] = $row['Fname'];
$result[$i]['mname'] = $row['Mname'];
$result[$i]['lname'] = $row['Lname'];
$i++;
}
echo json_encode($result);
?>

Categories