Unserialize function doesn't return array values - php

Hello i want to unserialize an array in order to display the array values.
The way that the array is inserted to my db field is like this.
persons: "a:1:{i:0;s:55:"[{"value":"john: writer"},{"value":"john: producer"}]";}"
and the function i have done but i am not getting any results is this
$adDetails = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($adDetails as $feed) {
$feed->logo_pic = SITE_URL . $feed->logo_pic;
$feed->image_path = SITE_URL . $feed->image_path;
$feed->media_pic = SITE_URL . 'mediaPic/' . $feed->media_pic;
$personsArr = unserialize(array($feed->persons));
$personsText = " ";
if(!empty($personsArr)){
list($firstItem) = $personsArr;
foreach ($firstItem as $key => $value) {
foreach ($value as $valueInner) {
$personsText .= $valueInner.", ";
}
}
}
$feed->personsNew = $personsText;
}
$response['success'] = true;
$response['adDetails'] = $adDetails;
echo json_encode($response);
I am getting nothing on personsText although persons is persons: "a:1:{i:0;s:55:"[{"value":"john: writer"},{"value":"john: producer"}]";}"
Any help?

The value in the array is a JSON string, so you need to decode it.
The argument to unserialize() should just be $feed->persons, it shouldn't be in an array.
Instead of the loop, you can use array_column() to get all the value elements, and implode() to combine them with comma delimiters.
$adDetails = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($adDetails as $feed) {
$feed->logo_pic = SITE_URL . $feed->logo_pic;
$feed->image_path = SITE_URL . $feed->image_path;
$feed->media_pic = SITE_URL . 'mediaPic/' . $feed->media_pic;
$personsArr = unserialize($feed->persons);
$personsText = " ";
if(!empty($personsArr)){
$firstItem = json_decode($personsArr[0], true);
$personsText = implode(', ', array_column($firstItem, 'value'));
}
$feed->personsNew = $personsText;
}
$response['success'] = true;
$response['adDetails'] = $adDetails;
echo json_encode($response);

Related

How to get the keys of each level of a multidimensional array in PHP [duplicate]

This question already has answers here:
PHP - Convert multidimensional array to 2D array with dot notation keys
(5 answers)
Closed 8 months ago.
I'm trying to grab all the keys of a multidimensional array and format them a certain way. Here's a partial array:
$ini_config['aaa']['email']['main'] = 'me#name.com';
$ini_config['bbb']['email']['ccc'] = 'you#name.com';
$ini_config['bbb']['phone']['local'] = '800-555-1212';
$ini_config['bbb']['phone']['skype'] = '744-222-1234';
$ini_config['ccc']['phone']['main'] = 'domain.com';
$ini_config['ccc']['domain']['https'] = 'https://www. domain.com';
$ini_config['ccc']['fax'] = '744-222-1237';
and here's the format I need them in:
aaa_email_main
bbb_email_ccc
bbb_phone_local
bbb_phone_skype
ccc_phone_main
ccc_domain_https
ccc_fax
This script is the closest I've been able to come to what I need:
<?php
rloop($ini_config);
function rloop($array) {
global $full_key;
foreach($array as $key => $value) {
if(is_array($value) ) {
$full_key .= $key .'_';
$array[$key] = rloop($array[$key]);
}
else {
$array[$key] = (string) $value;
$filename = $full_key . $key;
echo 'filename: '. $filename . PHP_EOL;
$full_key = '';
}
}
}
N.B. The number of levels can be from 1 to 4, and all keys are strings.
Thanks
$ini_config['aaa']['email']['main'] = 'me#name.com';
$ini_config['bbb']['email']['ccc'] = 'you#name.com';
$ini_config['bbb']['phone']['local'] = '800-555-1212';
$ini_config['bbb']['phone']['skype'] = '744-222-1234';
$ini_config['ccc']['phone']['main'] = 'domain.com';
$ini_config['ccc']['domain']['https'] = 'https://www. domain.com';
$ini_config['ccc']['fax'] = '744-222-1237';
function keyPaths(array $array, array $carry = [], string $separator = ''): array {
foreach ($array as $key => $value) {
if (is_array($value)) {
$carry = keyPaths($value, $carry, $separator . $key . '_');
} else {
$carry[] = $separator . $key;
}
}
return $carry;
}
$result = keyPaths($ini_config);
Thanks to #lucas.j here's what I'm using now:
function get_all_keys($array, $collector='') {
$separator = '_';
foreach ($array as $key => $value) {
if (is_array($value)) {
get_all_keys($value, $collector.$key.$separator);
}
else {
$filename = $collector.$key;
$content = $value;
// echo 'filename: '. $filename . PHP_EOL; //:debug
// echo 'content: ' . $content . PHP_EOL; //:debug
file_put_contents($filename, $content);
}
}
}
After adding strategically placed echo statements, I was able to see what the $separator variable was doing. So I renamed it to $collector, since it's collecting the keys to form the "all-keys" string. I also renamed the function to be a little more descriptive, and added the hard-coded underscore to a new variable called $separator.
And since I don't need a new variable created, I dropped $carry and am performing what I need done directly in the else section.
Thanks, Lucas!

Create a list like array when echoed in php

I would like to echo my results from a database and have them look like an array. They don't necessarily have to be an array but look like one. i.e. When i echo my result,
i would want my final result to look like
[10,200,235,390,290,250,250]
When i try the code below:
$query_rg = mysqli_query($link, "SELECT column FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {
$list = $row['column'];
$listwithcoma = "$list,";
echo ltrim($listwithcoma,',');
}
echo ']'
The result is :
[10,200,235,390,290,250,250,]
You are doing it wrong. ltrim($listwithcoma,',') has no effect.
ltrim — Strip whitespace (or other characters) from the beginning of a string
You can try a simple way with implode.
$list = array();
while ($row = mysqli_fetch_assoc($query_rg)) {
$list[] = $row['column'];
}
echo '[' . implode(',', $list) . ']';
Just use GROUP_CONCAT in query as
$query_rg = mysqli_query($link, "SELECT GROUP_CONCAT(`column` SEPARATOR ', ') as data
FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
print_r($row_rg['data']);
Try like this
$list = array(); //define a array.
while ($row = mysqli_fetch_assoc($query_rg)) {
$list[] = $row['column']; //store column value in array.
}
$lists = "[".implode(",",$list)."]";
echo $lists; //will echo your results.
You should be using rtrim() function instead, that too outside the loop.
$listwithcoma = '';
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {
$list = $row['column'];
$listwithcoma .= "$list,";
// echo ltrim($listwithcoma,','); Remove this
}
echo rtrim($listwithcoma,','); // Add this
echo ']';

Confusion how to handle array return

function get_galleryxml_row($table_data)
{
$xml_output = array();
if ($table_data)
{
foreach($table_data as $key => $row)
{
$xml_output[] .= $this->exporter->get_property_gallery_data($key['id']);
}
return implode(" ", $xml_output);
}
}
get_property_gallery_data Returns area of images and urls which does contain data and I have checked but some reason i am getting the follow error.
Array to string conversion and it states this line as the error
$xml_output[] .= $this->exporter->get_property_gallery_data($key['id']);
No need of . -
$xml_output[] = $this->exporter->get_property_gallery_data($row['id']); // It should be only $key or $row['id']
It will store the value with new index. . is used to concatenate strings.
Try this...
$xml_output[] .= $this->exporter->get_property_gallery_data($key['id']);
to
$xml_output[] = $this->exporter->get_property_gallery_data($row['id']);

array result using foreach statement display in json in php

I am getting the result from web service SOAP client. I have created an array to get the result and display it using json format. I am getting few of my results properly. I have SerialEquipment parameter which is array and i need to get the result using foreach loop. I am doing an mistake there. I dont know how can i assign my $vehiclResult array in this for each statement. So that all the results at last i will collect and display using json using vehicleResult array.My mistake is in the foreach loop.
structure for SerialEquipment parameters:
Code:
$vehicle = getVehicleValuation();
$Serial=$vehicle['SerialEquipment'];
$vehiclResult = array(
'WE_Number' => $vehicle['WE Number'] ."<br>",
'Vehicle Type'=> $vehicle['Vehicle Type'] . "<br>",
'HSN' => $vehicle['HSN'] . "<br>",
'TSN' => $vehicle['TSN'] . "<br>"
);
foreach($Serial as $key => $obj) {
if(!isset($vehiclResult[$key]))
$vehiclResult[$key] = array();
$vehiclResult[$key]['SerialEquipment'] = $key. "<br>";
$vehiclResult[$key]['Code'] = $obj->Code. "<br>";
$vehiclResult[$key]['Desc Short'] = $obj->Desc_Short. "<br>";
$vehiclResult[$key]['Desc Long'] = $obj->Desc_Long. "<br>";
foreach($obj->Esaco as $key2 => $obj2) {
if($obj2->EsacoMainGroupCode === null){
// doesn't contain Esaco
continue;
}
else{
if(!isset($vehiclResult[$key][$key2]))
$vehiclResult[$key][$key2] = array();
$vehiclResult[$key][$key2]['esaco'] = $key2. "<br>";
$vehiclResult[$key][$key2]['EsacoMainGroupCode'] = $obj2->EsacoMainGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoMainGroupDesc'] = $obj2->EsacoMainGroupDesc. "<br>";
$vehiclResult[$key][$key2]['EsacoSubGroupCode'] = $obj2->EsacoSubGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoSubGroupDesc'] = utf8_decode($obj2->EsacoSubGroupDesc). "<br>";
$vehiclResult[$key][$key2]['EsacoGroupCode'] = $obj2->EsacoGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoGroupDesc'] = utf8_decode($obj2->EsacoGroupDesc). "<br>";
}
}
}
$result = array(
'vehicle' => $vehiclResult
);
echo json_encode($result);
die();
}
You need to check if your array have the key so:
if(!isset($vehiclResult[$key]))
if not, you need to create it:
$vehiclResult[$key] = array(); // as an array
Also, you don't really need to make a description of your "item". You can Parse your JSON on the result page to output some text.
You can do something like.
Do something like:
foreach($Serial as $key => $obj) {
if(!isset($vehiclResult[$key]))
$vehiclResult[$key] = array();
$vehiclResult[$key]['serial'] = $key;
$vehiclResult[$key]['code'] = $obj->Code;
$vehiclResult[$key]['short_desc'] = $obj->Desc_Short;
$vehiclResult[$key]['long_desc'] = $obj->Desc_Long;
foreach($obj->Esaco as $key2 => $obj2) {
if($obj2->EsacoMainGroupCode === null){
// doesn't contain Esaco
continue;
}
else{
if(!isset($vehiclResult[$key][$key2]))
$vehiclResult[$key][$key2] = array();
$vehiclResult[$key][$key2]['esaco'] = $key2;
$vehiclResult[$key][$key2]['EsacoMainGroupCode'] = $obj2->EsacoMainGroupCode;
$vehiclResult[$key][$key2]['EsacoMainGroupDesc'] = $obj2->EsacoMainGroupDesc;
$vehiclResult[$key][$key2]['EsacoSubGroupCode'] = $obj2->EsacoSubGroupCode;
$vehiclResult[$key][$key2]['EsacoSubGroupDesc'] = utf8_decode($obj2->EsacoSubGroupDesc);
$vehiclResult[$key][$key2]['EsacoGroupCode'] = $obj2->EsacoGroupCode;
$vehiclResult[$key][$key2]['EsacoGroupDesc'] = utf8_decode($obj2->EsacoGroupDesc);
}
}
}
$result = array(
'vehicle' => $vehiclResult
);
echo json_encode($result);
die();
If you would keep your "text" and your <br> code, do the samething but add what you want to output after the "="
EDIT
** A HAVE CHANGE THE CODE PREVIOUSLY..
if you want to test your $vehiclResult, try something like:
foreach($vehiclResult as $key=>$value){
if(!is_array($value))
var_dump($value);
else {
foreach($value as $key2=>$value2){
if(!is_array($value2))
var_dump($value2);
else {
foreach($value2 as $key3=>$value3){
var_dump($value3);
}
}
}
}

dynamic variables from array

I store the field names within an array, in hopes to dynamically create the variables.
I receive a illegal offset type error for the if and else, these two lines:
$data[$tmp_field] = $tmp_field[$id];
$data[$tmp_field] = 0;
I checked the post data and it is posting with the appropriate data, but I am not sure what the problem is.
$student_id stores all the students ids., for example: $student_id = array(8,9,11,23,30,42,55);
function updateStudentInfo() {
$student_id = $this->input->post('student_id');
$internet_student = $this->input->post('internet_student');
$dismissed = $this->input->post('dismissed');
$non_matriculated_student = $this->input->post('non_matriculated_student');
$felony = $this->input->post('felony');
$probation = $this->input->post('probation');
$h_number = $this->input->post('h_number');
$office_direct_to = $this->input->post('office_direct_to');
$holds = $this->input->post('holds');
$fields = array('internet_student', 'non_matriculated_student', 'h_number', 'felony', 'probation', 'dismissed');
foreach($student_id as $id):
$data = array();
foreach($fields as $field_name):
$tmp_field = ${$field_name};
if(empty($tmp_field[$id])) {
$data[$tmp_field] = 0;
} else {
$data[$tmp_field] = $tmp_field[$id];
}
endforeach;
print '<pre style="color:#fff;">';
print_r($data);
print '</pre>';
endforeach;
}
This is the array format I desire:
Array
(
[internet_student] => 1
[non_matriculated_student] => 1
[h_number] => 0
[felony] => 0
[probation] => 1
[dismissed] => 0
)
Added screenshot to give you a visual of the form the data is being posted from
foreach($student_id as $id):
$data = array();
foreach($fields as $field_name):
$tmp_field = ${$field_name};
if(empty($tmp_field[$id])) {
$data[$field_name] = 0;
} else {
$data[$field_name] = $tmp_field[$id];
}
endforeach;
print '<pre style="color:#fff;">';
print_r($data);
print '</pre>';
endforeach;
I am assuming that all these fields are arrays, as otherwise you wouldn't need any loops.
function updateStudentInfo()
{
$student_id = $this->input->post('student_id');
$internet_student = $this->input->post('internet_student');
$dismissed = $this->input->post('dismissed');
$non_matriculated_student = $this->input->post('non_matriculated_student');
$felony = $this->input->post('felony');
$probation = $this->input->post('probation');
$h_number = $this->input->post('h_number');
$office_direct_to = $this->input->post('office_direct_to');
$holds = $this->input->post('holds');
$fields = array('internet_student', 'non_matriculated_student', 'h_number', 'felony', 'probation', 'dismissed');
$student_count = count($student_id);
foreach($student_id as $id)
{
$data = array();
foreach($fields as $field)
{
if(array_key_exists($id, $$field))
$data[$field] = ${$field}[$id];
}
}
}
You are trying to use the student id as an array key for the other fields but the HTML form is just a standard indexed array, not keyed to any student data.

Categories