how to convert stdobj array to associative array in php - php

I have this stdclass object in array
Array ( [0] => stdClass Object ( [file_id] => 6 [file_name] => 1ofdays.wav ) [1] => stdClass Object ( [file_id] => 7 [file_name] => abcd.mp3 ) )
I want to convert this stdclass object array into associative arrays such as
$name_array=([text]=>1ofdays.wav,[text]=>abcd.mp3);
$id_array=([value]=>6,[value]=>7);
I tried achieving it by first flattening the array using this function
public function array_flatten($mArray) {
$sArray = array();
foreach ($mArray as $row) {
if ( !(is_array($row)) ) {
if($sArray[] = $row){
}
} else {
$sArray = array_merge($sArray,$this->array_flatten($row));
}
}
return $sArray;
}
This function gave me result
Array ( [0] => 6 [1] => 1ofdays.wav [2] => 7 [3] => abcd.mp3 )
then I created two arrays even() and odd()
and took elements from odd and even indexes of the and pushed them in their respected arrays
which resulted in
even( [0] => 6 [1] => 7 )
odd( [0] => 1ofdays.wav [1] => abcd.mp3 )
now i want to put elements of even array into
Id_array =('value'=>6,'value'=>7)
and
name_array=('text'=>1ofdays.wav,'text'=>'abcd.mp3')

Hope It is same as you want
<?php
class stdClass1 {
public $file_id;
public $file_name;
public function setName($n, $sn) {
$this->file_id = $n;
$this->file_name = $sn;
}
}
$exaObj = new stdClass1;
$exaObj2 = new stdClass1;
$exaObj->setName('6', '1ofdays.wav');
$exaObj2->setName('7', 'abcd.mp3');
$arr = array($exaObj, $exaObj2);
foreach ($arr as $k => $v) {
print_r($v);
echo "<br>";
foreach ($v as $key => $value) {
$$key[] = $value;
}
}
echo "<pre>";
print_r($file_id);
echo "</pre>";
echo "<pre>";
print_r($file_name);
echo "</pre>";
echo "Second METHOD<br><br>";
foreach ($arr as $k => $v) {
$nameArr[] = $v->file_name;
$idArr[] = $v->file_id;
}
echo "<pre>";
print_r($idArr);
echo "</pre>";
echo "<pre>";
print_r($nameArr);
echo "</pre>";
?>

Related

How to parse arrays with different levels PHP

In a foreach loop i would like to compare [name] value beetween different arrays but they have not the same levels.
Array(
[array1] => Array
(
[0] => WP_Term Object
(
[name] => Plafond
)
)
[array2] => WP_Term Object
(
[name] => Chaudière
)
[array3] => Array
(
[0] => WP_Term Object
(
[name] => Pla
)
[1] => WP_Term Object
(
[name] => Toc
)
)
)
I don't know how could i get the [name] in the same loop whereas levels are different.
I have tried to make :
foreach( $fields as $name => $value )
{
echo $value->name; }
Should i add another loop in the first loop ?
thanks
So your data looks like this:
$json = '{"array1":[{"name":"Plafond"}],"array2":{"name":"Chaudière"},"array3":[{"name":"Pla"},{"name":"Toc"}]}';
$array = json_decode($json);
If you don't know how deep it will go, a simple recursive function should work. Perhaps something like this:
function get_name($o, &$output) {
if (is_array($o)) {
foreach($o as $v) {
get_name($v, $output);
}
} elseif (property_exists($o, "name")) {
$output[] = $o->name;
}
}
$output = [];
foreach ($array as $v) {
get_name($v, $output);
}
If you data is going to look like the sample you provided (i.e. it will always be first or second level) then you don't need to worry about recursion.
$output = [];
foreach ($array as $k=>$v) {
if (is_array($v)) {
foreach ($v as $k2=>$v2) {
$output[] = $v2->name;
}
} else {
$output[] = $v->name;
}
}
Either way, your output values are all in the $output array:
print_r($output);
Output:
Array
(
[0] => Plafond
[1] => Chaudière
[2] => Pla
[3] => Toc
)
You can use array_map, array_key_exists to retrive the name index from the array
$jsonFormat = '{"array1":[{"name":"Plafond"}],"array2":{"name":"Chaudière"},"array3":[{"name":"Pla"},{"name":"Toc"}]}';
$jsonArray = json_decode($jsonFormat,true);
$res = [];
array_map(function($v) use (&$res){
if(array_key_exists('name', $v)){
$res[] = $v['name'];
}else{
foreach($v as $_key => $_value){
$res[] = $_value['name'];
}
}
}, $jsonArray);
echo '<pre>';
print_r($res);
Result:-
Array
(
[0] => Plafond
[1] => Chaudière
[2] => Pla
[3] => Toc
)
You can use $res to compare the names.

Fetch values from multi dimensional array

I need to fetch data from the array that I got through
print_r($result);
The array I got is
Array
(
[0] => Array
(
[id] =>
[Location] => Array
(
[img] => 177223
[name] =>
)
[Max] =>
[Total] =>
[Description] => Array
(
[Pre] =>
[Updated] =>
[Program] => Array
(
[Schedule] =>
)
)
[Staff] => Array
(
[FirstName] =>
)
)
)
I used this code
if (!empty($result))
{
foreach ($result as $res)
{
$Max = $res['Max'];
echo $Max;
echo "<br>";
if(isset($res['Location']))
{
foreach($res['Location'] as $loc)
{
$img= $loc['img'];
echo $img;
echo "<br>";
}
}
}
}
I am getting correct value for the first array (I.e Max etc) but not for Location, Description and Staff, can anyone correct my code
Location is not an array of arrays.
It is just an associative array.
if (!empty($result)) {
foreach ($result as $res) {
$Max = $res['Max'];
echo $Max;
echo "<br>";
if(isset($res['Location'])) {
$img= $res['Location']['img'];
echo $img;
echo "<br>";
}
}
}
You dont need to foreach through location, just access it's elements directly:
if(isset($res['Location']))
{
$img= $res['Location']['img'];
echo $img;
echo "<br>";
}
Or somethig like that.

Edit an array with new values in PHP

I have this array:
Array
(
[datas] => Array
(
[General] => Array
(
[0] => Array
(
[id] => logo
[size] => 10
)
)
[Rooms] => Array
(
[0] => Array
(
[id] => room_1
[size] => 8
)
[1] => Array
(
[id] => room_2
[size] => 8
)
[2] => Array
(
[id] => room_3
[size] => 8
)
)
)
)
I need to update it when I receive some info like this:
$key = 'room_3';
$toChange = '9';
So in my array, I want to change the size of room_3.
I will always edit the same element (i.e. size).
What I tried:
// Function to communicate with the array
getDatas($array, 'room_3', '9');
function getDatas($datas, $got, $to_find) {
foreach ($datas as $d) {
if (array_search($got, $d)) {
if (in_array($to_find, array_keys($d))) {
return trim($d[$to_find]);
}
}
}
}
But it does not work...
Could you please help me ?
Thanks.
function getDatas($datas, $got, $to_find) {
foreach($datas['datas'] as $key => $rows) {
foreach($rows as $number => $row) {
if($row['id'] == $got) {
// u can return new value
return $row['size'];
// or you can change it and return update array
$datas['dates'][$key][$number]['size'] = $to_find; // it should be sth like $new value
return $datas;
}
}
}
}
function changeRoomSize (&$datas, $roomID, $newSize ){
//assuming that you have provided valid data in $datas array
foreach($datas['datas']['Rooms'] as &$room){
if($room['id'] == $roomID){
$room['size'] = $newSize;
break;//you can add break to stop looping after the room size is changed
}
}
}
//--- > define here your array with data
//and then call this function
changeRoomSize($data,"room_3",9);
//print the results
var_dump($data);
It's a 3-dimensional array, if you want to change the value, do like this:
$key = 'room_3';
$toChange = '9';
$array['datas'] = getRooms($array['datas'], $key, $toChange);
function getRooms($rooms, $key, $toChange) {
foreach($rooms as $k1=>$v1) foreach ($v1 as $k2=>$v2) {
if ($v2['id'] == $key)) {
$rooms[$k1][$k2]['size'] = $toChange;
}
}
return $rooms;
}
print_r($array);

how to match some elements in associative array in php

I have a following array
Array
(
[0] => Array
(
[0] =>
)
[1] => Array
(
[0] => flatrate
[1] => flatrate3
[2] => freeshipping
)
[2] => Array
(
[0] => flatrate
[1] => flatrate2
[2] => flatrate3
[3] => flatrate4
[4] => freeshipping
)
)
Now, i need to match some element in this like
if freeshipping in above array . it should echo yes else no.
Please suggest, how can i do this.
for($i = 0; count($array); $i++){
if(in_array($string, $array[$i]) echo true;
}
you can do simple code like that :
foreach ($array as $key) {
foreach ($key as $value) {
if($value == "your condition")
{
echo 'yes';
}else{
echo 'no';
}
}
}
try it.
Create A function
function checkfreeShipping($arrData)
{
foreach($arrData as $data){
if(in_array('freeshipping',$data))
return true;
}
}
Call defined function to check Shipping -
if(checkfreeShipping($cartArr)){
echo "free Shipping";
}
else{
echo "Paid Shipping";
}

PHP Array and current()

I have an array in the format
Array
(
[/Callum/] => Array
(
[0] => ##chan1
)
[/Adam/] => Array
(
[0] => ##chan2
)
[/Chris)/] => Array
(
[0] => ##chan1
)
[/Mike*/] => Array
(
[0] => ##chan3
)
)
And from this I use the below code to try and get the id of the array that each channel features in.
foreach($array as $row)
{
if (in_array($buf['channel'],$row))
{
$return = $return." ".current(array_keys($array,$row));
}
}
My problem is that current() doesnt seem to work the way I am expecting it to. Currently if the $buf /Callum/ twice rather than /Callum/ and /Chris/
Why not:
foreach($array as $key => $row)
{
if (in_array($buf['channel'],$row))
{
$return = $return . " " . $key;
}
}
Try this instead
foreach($array is $id => $row){
$return .=" ".$id;
}
edit:
foreach($array is $id => $row){
if($row[0] == $buf['channel']){
echo $key; //This is your key
}
}

Categories