How to flatten this array of objects in PHP? - php

I have an array like this:
Array
(
[0] => stdClass Object
(
[㐀] => Array
(
[0] => jau1
)
)
[1] => stdClass Object
(
[㐁] => Array
(
[0] => dou6
)
)
[2] => stdClass Object
(
[㐂] => Array
(
[0] => cat1
)
)
)
How can I remove the stdClassObject for every element in this array?
Since the key for each element is different, I guess array_column is not going to work.

you could just iterate the data and get what you want:
$res = array();
foreach ($array as $key => $val) {
foreach ($val as $keyObj => $valObj) {
$res[$keyObj] = $valObj[0];
}
}
var_dump($res);
This outputs:
array(3) {
["㐀"]=>
string(4) "jaul"
["㐁"]=>
string(4) "dou6"
["㐂"]=>
string(4) "cat1"
}
online demo

suppose.. $array is your main array
you can try (if you want to convert object array element to array):
$arrCnt = count($array);
for($i=0;$i<$arrCnt;$i++) $array[$i] = (array) $array[$i];
actually you have not mentioned your query exactly. Its confusing
Or
If you want to skip stdObject from that then you can try:
$arrCnt = count($array);
$newArr = array();
for($i=0;$i<$arrCnt;$i++){
$array[$i] = (array) $array[$i];
foreach($array[$i] as $k=>$v) $newArr[$k] = $v[0];
}
print_r();

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.

Convert index array into multidimensional associative/index array in php

My array looks like this
Array
(
[0] => A
[1] => B
[2] => C
)
Desired array
Array
(
[0] => Array
(
[0] => A
)
[1] => Array
(
[0] => B
)
[2] => Array
(
[0] => C
)
)
I have gone through these links but didn't able to figure out the solution being a newbie.
Convert associative array into indexed
convert indexed multidimensional array to associative multidimensional array
For example:
$new_array = array_map(
function ($v) { return [$v]; },
['A', 'B', 'C']
);
This is a blanket statement on how to get your desired array :
$desired_array = array(array("0"=>"A"), array("0"=>"B"), array("0"=>"C"));
However, dynamically, you could do the following :
//Assume $original_array = array("0"=>"A", "1"=>"B", "2"=>"C");
$desired_array = array(); // New Array
for($i = 0; $i < count($original_array); $i++){ // Loop over all elements in original array
array_push($desired_array, array("0"=>$original_array[$i])); // Place each valueable as an array in new desired array
}
$arrOld = ['A','B','C','D','E'];
$arrNew = [];
foreach($arrOld as $key => $value){
$arrNew[] = [$key => $value];
}

PHP Transform multiple objects into one array

Whilst trying to transform multiple objects and put them into one array I unfortunately get a array-in-array result.
The objects I would like to transform:
array(2) {
[0]=>
object(stdClass)#104 (1) {
["name"]=>
string(4) "Paul"
}
[1]=>
object(stdClass)#105 (1) {
["name"]=>
string(5) "Jenna"
}
}
My PHP:
for ($i=0; $i < count($readers) ; $i++) {
$json = json_encode($readers[$i]); // 1
$data = json_decode($json, TRUE); // 2
$arr = array();
array_push($arr, $data); // 3
}
The outputs:
// 1
{"name":"Paul"}{"name":"Jenna"}
-
// 2
Array
(
[name] => Paul
)
Array
(
[name] => Jenna
)
-
// 3
Array
(
[0] => Array
(
[name] => Paul
)
)
Array
(
[0] => Array
(
[name] => Jenna
)
)
Desired Outcome
I would like to have everything merged into one array. The key is the index and the value is the name.
Array
(
[0] => Paul
[1] => Jenna
)
Loop through the array of objects ($arr) and compile the final array ($finArr) with the $val->string value. Try this:
$finArr = array();
foreach ($arr as $key => $val) {
$finArr[] = $val->string;
}
You can simply iterate through the array of readers, pull out the name of each reader, and add each of their names to a numerically indexed array as you desire.
$names = array(); // Initialize.
foreach($readers as $reader) {
if (!empty($reader->name)) {
$names[] = $reader->name;
}
}
print_r($names); // To see what you've got.
Array
(
[0] => Paul
[1] => Jenna
)
You have to extract key also from array. And declare $arr = array() outside foreach
$arr = array();
for ($i=0; $i < count($readers) ; $i++) {
$data = $readers[$i]->name; //change this line
array_push($arr, $data); // 3
}
print_r($arr);
Another way is you can simply use array_column()
$arr = array_column($readers,"name");
print_r($arr);

Explode multiple comma-separated strings in a 2d array, then get all unique values

I have an 2d array which returns me this values:
Array (
[0] => Array (
[0] => wallet,pen
[1] => perfume,pen
)
[1] => Array (
[0] => perfume, charger
[1] => pen,book
).
Out of this i would like to know if it is possible to create a function which would combine the array going this way,and create a new one :
if for example [0] => Array ( [0] => wallet,pen [1] => perfume,pen ) then should be equal to
[0] => Array ( [0] => wallet,pen, perfume ) because there is a common word else do nothing.
And also after that retrieve each words as strings for further operations.
How can i make the values of such an array unique. Array ( [0] => Array ( [0] => wallet [1] => pen [2] => perfume [3] => pen) ) as there is pen twice i would like it to be deleted in this way ( [0] => Array ( [0] => wallet [1] => pen [2] => perfume) )
It's just a matter of mapping the array and combining the inner arrays:
$x = [['wallet,pen', 'perfume,pen'], ['perfume,charger', 'pen,book']];
$r = array_map(function($item) {
return array_unique(call_user_func_array('array_merge', array_map(function($subitem) {
return explode(',', $subitem);
}, $item)));
}, $x);
Demo
This first splits all the strings based on comma. They are then merged together with array_merge() and the duplicates are removed using array_unique().
See also: call_user_func_array(), array_map()
Try this :
$array = Array (Array ( "wallet,pen", "perfume,pen" ), Array ( "perfume, charger", "pen,book" ));
$res = array();
foreach($array as $key=>$val){
$temp = array();
foreach($val as $k=>$v){
foreach(explode(",",$v) as $vl){
$temp[] = $vl;
}
}
if(count(array_unique($temp)) < count($temp)){
$res[$key] = implode(",",array_unique($temp));
}
else{
$res[$key] = $val;
}
}
echo "<pre>";
print_r($res);
output :
Array
(
[0] => wallet,pen,perfume
[1] => Array
(
[0] => perfume, charger
[1] => pen,book
)
)
You can eliminate duplicate values while pushing them into your result array by assigning the tag as the key to the element -- PHP will not allow duplicate keys on the same level of an array, so any re-encountered tags will simply be overwritten.
You can use recursion or statically written loops for this task.
Code: (Demo)
$result = [];
foreach ($array as $row) {
foreach ($row as $tags) {
foreach (explode(',', $tags) as $tag) {
$result[$tag] = $tag;
}
}
}
var_export(array_values($result));
Code: (Demo)
$result = [];
array_walk_recursive(
$array,
function($v) use(&$result) {
foreach (explode(',', $v) as $tag) {
$result[$tag] = $tag;
}
}
);
var_export(array_values($result));

Array value and index migration

My array is like:
Array
(
[0] => Array
(
[0] => "name"
[1] => "zxczxc5"
)
[1] => Array
(
[0] => "about"
[1] => "zxczxc"
)
[2] => Array
(
[0] => "contact"
[1] => "zxczxc"
)
)
I want to generate another array like this :
Array
{
['name']="zxczxc5";
}
Array
{
['contact']="zxczxc";
}
Array
{
['about']="zxczxc";
}
I want the first array index zero value goes as the index of second value in my new array.
Thanks.
There are many ways to solve what you want to achieve, this is just one of those:
foreach ($array as &$pair) {
$pair = call_user_func_array('array_combine', $pair);
}
unset($pair);
print_r($array);
It makes use of array_combine.
Assuming you name your first Array $aTest:
foreach($aTest as $aElement)
{
$aNewArray[$aElement[0]] = $aElement[1];
}
print_r($aNewArray);
foreach ($array as $value) {
$newArray[$value['0']] = $value['1'];
}
Assuming the first array is called $array
$new_array = array();
foreach($array as $element)
{
$new_array[] = array($element[0] => $element[1]);
}
$newArr = array();
foreach($arr as $val) {
$newArr[$val[0]] = $val[1];
}

Categories