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);
Related
I have this problem. I have a multidimensional json array (don't ask - legacy code). I convert it to PHP array. I need to extract all KEYS that have EQUAL VALUE (in my case "666"). I need each key to be assign to a SEPARATE variable. In my code I succeeded to fetch the keys but I can assign them only to another array or all at once to a single variable. Please HELP!!!
Love V
Here is the code:
<?php
//user input
$in = "666";
$outputZ = '[
{"record_id_001":"1"},
{"record_id_002":"13"},
{"record_id_003":"666"},
{"record_id_004":"72661781"},
{"record_id_005":"8762"},
{"record_id_006":"666"},
{"record_id_007":"8762"},
{"record_id_008":"666"},
{"record_id_009":"8762"},
{"record_id_010":"8762"},
{"record_id_011":"666"}
]';
//convert json to php array
//someArray = json_decode($someJSON, true);
$decoZ = json_decode($outputZ, true);
// TESTING (move to comment latter)
//print_r ($decoZ);
//loop through each array an check for user input
//way 1: assign to new array
foreach($decoZ as $array => $number)
foreach($number as $key => $value)
if (in_array("$in", $number)) {
$var = $key;
$getarray = "'" . $var . "'";
$recnumber = array($getarray);
print_r ($recnumber);
}
//way 2: assign to variable
foreach($decoZ as $array => $number)
foreach($number as $key => $value)
if (in_array("$in", $number)) {
$var = $key;
echo "$var" . " ";
}
?>
You're overwritting your array on each iterations $recnumber = array($getarray);
I would rather follow this logic :
<?php
//user input
$in = "666";
$outputZ = '[
{"record_id_001":"1"},
{"record_id_002":"13"},
{"record_id_003":"666"},
{"record_id_004":"72661781"},
{"record_id_005":"8762"},
{"record_id_006":"666"},
{"record_id_007":"8762"},
{"record_id_008":"666"},
{"record_id_009":"8762"},
{"record_id_010":"8762"},
{"record_id_011":"666"}
]';
$decoZ = json_decode($outputZ, true);
// create empty array
$recnumber = [];
foreach($decoZ as $record)
{
foreach($record as $key => $value)
{
// simply compare input with current value
if ($value === $in)
{
// add the key to the previously created array
$recnumber[] = $key;
}
}
}
var_dump($recnumber);
This outputs :
array(4) {
[0]=>
string(13) "record_id_003"
[1]=>
string(13) "record_id_006"
[2]=>
string(13) "record_id_008"
[3]=>
string(13) "record_id_011"
}
You can simply remap the records.
At the end you can grab them like
$codes666 = $ids['666'];
$outputZ = '[
{"record_id_001":"1"},
{"record_id_002":"13"},
{"record_id_003":"666"},
{"record_id_004":"72661781"},
{"record_id_005":"8762"},
{"record_id_006":"666"},
{"record_id_007":"8762"},
{"record_id_008":"666"},
{"record_id_009":"8762"},
{"record_id_010":"8762"},
{"record_id_011":"666"}
]';
$records = json_decode($outputZ);
$ids = [];
foreach($records as $record) {
foreach($record as $key => $value) {
$ids[(string)$value][] = $key;
}
}
print_r($ids);
Gives
Array
(
[1] => Array
(
[0] => record_id_001
)
[13] => Array
(
[0] => record_id_002
)
[666] => Array
(
[0] => record_id_003
[1] => record_id_006
[2] => record_id_008
[3] => record_id_011
)
[72661781] => Array
(
[0] => record_id_004
)
[8762] => Array
(
[0] => record_id_005
[1] => record_id_007
[2] => record_id_009
[3] => record_id_010
)
)
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();
I have a 2 Dimentional array in php as follow :
Array
(
[0] => Array
(
[0] => 10
[1] =>
)
[1] => Array
(
[0] => 67
[1] =>
)
[2] => Array
(
[0] => 67
[1] => 50
)
)
I want to manipulate it as follow:
Array
(
[0] => Array
(
[0] => 10
[1] => 67
[2] => 67
)
[1] => Array
(
[0] =>
[1] =>
[2] => 50
)
)
Means I want to take first elements of all inner arrays in one array and 2nd element in another array.
How can I manipulate this. Plz help
You can array_map() instead of loop. Example:
$newArr[] = array_map(function($v){return $v[0];},$arr);
$newArr[] = array_map(function($v){return $v[1];},$arr);
Or can use array_column() if your PHP 5.5+
$newArr[] = array_column($arr, 0);
$newArr[] = array_column($arr, 1);
print '<pre>';
print_r($newArr);
print '</pre>';
Just run the following script:
$array1 = array();
for ($i = 0; $i < count($array1); $i++) {
for ($j = 0; $j < count($array1[$i]); $j++) {
$array2[$j][$i] = $array1[$i][$j];
}
}
Here's a general solution that works regardless of how many items you have in the array and the sub-arrays:
// Set up an array for testing
$my_array = array( array(10, null), array(67, null), array(67, 50));
/**
* Our magic function; takes an array and produces a consolidated array like you requested
* #param array $data The unprocessed data
* #return array
*/
function consolidate_sub_arrays($data)
{
/**
* The return array
* #var array $return_array
*/
$return_array = array();
// Loop over the existing array
foreach ($data as $outer) {
// Loop over the inner arrays (sub-arrays)
foreach($outer as $key => $val) {
// Set up a new sub-array in the return array, if it doesn't exist
if (!array_key_exists($key, $return_array)) {
$return_array[$key] = array();
}
// Add the value to the appropriate sub-array of the return array
$return_array[$key][] = $val;
}
}
// Done!
return $return_array;
}
// Just to verify it works; delete this in production
print_r(consolidate_sub_arrays($my_array));
You need to loop over the initial array and create a new array in the format you want it.
$new_array = array();
foreach ($input_array as $in ) {
$new_array[0][] = $in[0];
$new_array[1][] = $in[1];
}
print_r($new_array);
How to merge many Arrays in php
$array1="Array ( [0] => mouse ) Array ( [0] => mac ) Array ( [0] => keyboard )";
how i can array like this
Array( [0] =>mouse [1] => mac [2] =>keyboard );
depending on how your arrays are being stored, there are a couple of options.
Here are 2 examples:
<?php
$old_array = array(
array('mouse'),
array('mac'),
array('keyboard')
);
$new_array = array();
foreach($old_array as $a){
$new_array[] = $a[0];
}
echo '<pre>',print_r($new_array),'</pre>';
//// OR ////
$array1 = array('mouse');
$array2 = array('mac');
$array3 = array('keyboard');
$new_array = array_merge($array1,$array2,$array3);
echo '<pre>',print_r($new_array),'</pre>';
You should use array_merge function of PHP.
This:
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
will return this:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
It's as easy as a piece of cake! :)
Try it: http://www.w3schools.com/php/showphp.asp?filename=demo_func_array_merge
Tutorials:
http://www.w3schools.com/php/func_array_merge.asp
http://php.net/array_merge
So you basically have an array of arrays. You can do this in the following way:
$array = array(array(0 => 'mouse'), array(1 => 'mac'), array(2 => 'keyboard'));
$mergedArray = array();
foreach ($array as $part) {
$mergedArray = array_merge($mergedArray, $part);
}
var_dump($mergedArray);
The result is exactly what you would expect:
array(3) {
[0]=>
string(5) "mouse"
[1]=>
string(3) "mac"
[2]=>
string(8) "keyboard"
}
If you also have scalars in the big array, you can modify the loop to the following:
foreach ($array as $part) {
if (!is_array($part)) {
$mergedArray[] = $part;
} else {
$mergedArray = array_merge($mergedArray, $part);
}
}
Note: This will merge all values from all sub arrays, it's not limited to one entry per sub array.
php array_merge() function, Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
Merge N number of array using $array = array_merge( $array1 , $array2, $array3 ..... $arrayN);
$array1 = array ( '0' => 'mouse' );
$array2 = array ( '0' => 'mac' );
$array3 = array ( '0' => 'keyboard' );
$array = array_merge( $array1 , $array2, $array3);
echo "<pre>";
print_r($array);
echo "</pre>";
O/P:
Array
(
[0] => mouse
[1] => mac
[2] => keyboard
)
More info: http://us2.php.net/array_merge
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));