PHP Str_replace is not working in foreach loop - php

Here is my code.
I am trying to get inspect link for steam item. I have tried to use preg_replace but no luck either.
$API_link = sprintf("http://steamcommunity.com/id/*steamid*/inventory/json/730/2?trading=1");
$json = file_get_contents($API_link);
$json_output = json_decode($json);
$result = $json_output;
$link = array();
$id = array();
foreach($result->rgDescriptions AS $item){
$empty = array();
$newstring = $item->actions[0]->link;
if($newstring == NULL){
continue;
} else {
$empty['link'] = $newstring;
array_push($link, $empty);
}
}
foreach($result->rgInventory AS $inventory){
$empty = array();
if($inventory->instanceid == 0){
continue;
} else {
$empty['id'] = $inventory->id;
array_push($id, $empty);
}
}
$array = array_merge($id, $link);
foreach($array AS $final){
$assetid = "%assetid%";
echo str_replace($assetid, $final['id'], $final['link']);
}
}
But its not working. Please see if you can help.

As I can see you have array of arrays:
// bracket squares equivalent of array() keyword PHP >=v5.4
// here is
// $link = array(['link'=>'url'],['link'=>'url'])
// $id = array(['id'=>'id'],['id'=>'id'])
// result will be:
// array(['link']=>'url'],['link'=>'url'],['id'=>'id'],['id'=>'id'])
$array = array_merge($id, $link);
foreach($array AS $final){
// here is the first $final
// array('link'=>'url')
$assetid = "%assetid%";
// but here is we try to get
// 'id' and 'link'
echo str_replace($assetid, $final['id'], $final['link']);
}
I think it's some kind of mistake.
Ok, some test script:
<?php
$a = array( array('link'=>'hello1'), array('link'=>'hello2'));
$b = array( array('id'=>'id0'), array('id'=>'id1'));
$c = array_merge($a, $b);
var_dump($c);
result:
array(4) {
[0] =>
array(1) {
'link' =>
string(6) "hello1"
}
[1] =>
array(1) {
'link' =>
string(6) "hello2"
}
[2] =>
array(1) {
'id' =>
string(3) "id0"
}
[3] =>
array(1) {
'id' =>
string(3) "id1"
}
}
array_merge doesn't mix your associative arrays between them nether all nor particular item (I hope I explain it correct)
of course
foreach ($c as $item) {
var_dump($item);
}
will enumerate all the items one by one
array(1) {
'link' =>
string(6) "hello1"
}
array(1) {
'link' =>
string(6) "hello2"
}
array(1) {
'id' =>
string(3) "id0"
}
array(1) {
'id' =>
string(3) "id1"
}
and there is no array that has both of them (link and id) in the item
This script can't associate link and id properly, cause some of links can be skipped by continue, some of id also can be skipped. And it will be just a random list of available information. You can stuck in the next situation:
- $links has first 10 links
- $id has 3,4,5,7,9,11
It's just a list. Even if you have only this pure info (no other details), you can't properly associate it between of them by using shown source.
Here is minimum 1 simple solutions:
don't skip, don't merge, just add an empty array, and your final loop will be like this:
$assetid = "%assetid%";
for ($link as $key=>$final) {
if (count($final) && count($id[$key])) {
echo str_replace($assetid, $id[$key]['id'], $final['link']);
} else {
// some of needed arguments absent
}
}

Description not enough. Maybe try dump some variables?
foreach($array AS $final){
$assetid = "%assetid%";
//Check what is in $final
var_dump($final);
echo str_replace($assetid, $final['id'], $final['link']);
}

Related

how to add child array with dynamic key in loop PHP

i have string like this
$string = 'root.1.child1.2.nextnode.3.anothernode.4.var';
exploded by "." and created array like this
$arr = array('root','1','child1','2','nextnode','3','anothernode','3','var');
how i can convert this array to something like this ?
it should be dynamically convert because in some cases nodes in string are in a number different with the sample .
["root"]=>
array(1) {
[1]=>
array(1) {
["child1"]=>
array(1) {
[2]=>
array(1) {
["nextnode"]=>
array(1) {
[3]=>
array(1) {
["anothernode"]=>
array(1) {
[3]=>
array(1) {
[var]=>
NULL
}
}
}
}
}
}
}
}
An example using recursive function.
$array = ['root', '1', 'child1', '2', 'nextnode', '3', 'anothernode', '3', 'var'];
function getNestedArray(array $arr, int $idx = 0) {
if ($idx + 1 <= count($arr)) {
return [$arr[$idx] => getNestedArray($arr, $idx + 1)];
}
return null;
}
$output = getNestedArray($array);
var_dump($output);
This can be quit easily achieved by referencing the output and looping over the exploded array:
$output = [];
$reference = &$output;
foreach ($arr as $el) {
if (is_numeric($el)) {
$el = (int)$el;
}
$reference = [];
$reference[$el] = null;
$reference = &$reference[$el];
}
This also checks whether the element is a number and casts it to an integer if it is. The $output variable will contain the final array.
You can use recursive function
to do though
$flatArray = array('root','1','child1','2','nextnode','3','anothernode','3','var'); // your array
function createNestedArray($flatArray)
{
if( sizeof($flatArray) == 1 ) {
return [ $flatArray[0] => null ]; // for the case that paramter has one member we need to return [ somename => null ]
}
$nestedArray[ $flatArray[0] ] = createNestedArray(array_slice($flatArray, 1)); // otherwise we need to call createNestedArray with rest of array
return $nestedArray;
}
$nestedArray = createNestedArray($flatArray); // the result

Removing a JSON record from .json file with PHP

I have a json file looking like this :
[["{\"id\":1474721566304,\"name\":\"GGG\",\"brand\":\"GG\",\"price\":\"3\"}"],["{\"id\":1474721570904,\"name\":\"GGGH\",\"brand\":\"GGH\",\"price\":\"4\"}"],["{\"id\":1474721574188,\"name\":\"GGGH\",\"brand\":\"GGHH\",\"price\":\"5\"}"]]
What I am trying to do is to remove a record from it by it's id. For this purpose I have the following PHP code :
<?php
$string = file_get_contents("products.json");
$json_a = json_decode($string, true); //turning JSON-string into an array containing JSON-strings
$arr = array();
foreach ($json_a as $key) {
array_push($arr,json_decode($key[0],true)); //and here you turning each of the JSON-strings into objects themselves
}
$data= $_GET['data'];
$i=0;
foreach($arr as $element) {
if($data == $element["id"]){
unset($arr[$i]);//removing the product by ID
}
$i++;
}
var_dump($arr);
$arr2 = array();
foreach ($arr as $key) {//trying to make it look like the original json.
array_push($arr2,json_decode($key[0],true));
}
//var_dump($arr2);
echo json_encode($arr2);
?>
What I am getting from this code is :
array(2) { [0]=> array(4) { ["id"]=> float(1474721566304) ["name"]=> string(3) "GGG" ["brand"]=> string(2) "GG" ["price"]=> string(1) "3" } [1]=> array(4) { ["id"]=> float(1474721570904) ["name"]=> string(4) "GGGH" ["brand"]=> string(3) "GGH" ["price"]=> string(1) "4" } }
I am really out of ideas how to make this array look like my original JSON shown first on this post. I tried many different things, but I couldn't make it work. My idea is after removing the record by it's ID to replace the old JSON with the new one that I am trying to construct here.
I am new to php and I'd appreciate any input on my issue.
First of all - your input JSON is wrong:
array (size=3)
0 =>
array (size=1)
0 => string '{"id":1474721566304,"name":"GGG","brand":"GG","price":"3"}' (length=58)
1 =>
array (size=1)
0 => string '{"id":1474721570904,"name":"GGGH","brand":"GGH","price":"4"}' (length=60)
2 =>
array (size=1)
0 => string '{"id":1474721574188,"name":"GGGH","brand":"GGHH","price":"5"}' (length=61)
You don't have 'id' nor 'name', 'GGG' and other keys. You just have one long string. You should remove unnecessary quotation marks. After that your JSON should look like this:
[[{"id":1474721566304,"name":"GGG","brand":"GG","price":"3"}],[{"id":1474721570904,"name":"GGGH","brand":"GGH","price":"4"}],[{"id":1474721574188,"name":"GGGH","brand":"GGHH","price":"5"}]]
And finally, your PHP code can be much shorter:
$json = "[[{\"id\":1474721566304,\"name\":\"GGG\",\"brand\":\"GG\",\"price\":\"3\"}],[{\"id\":1474721570904,\"name\":\"GGGH\",\"brand\":\"GGH\",\"price\":\"4\"}],[{\"id\":1474721574188,\"name\":\"GGGH\",\"brand\":\"GGHH\",\"price\":\"5\"}]]";
$input = json_decode($json, true);
$output = array();
foreach($input as $element) { //you don't need to declare yet another array, just use the one you already have
if($_GET['data'] != $element[0]["id"]){ //and not unset, just add to new array if you want
$output[] = $element; //shorter and faster than array_push()
}
}
echo json_encode($output);
Try this code:
$string = file_get_contents("product.json");
$json_a = json_decode($string, true); //turning JSON-string into an array containing JSON-strings
$arr = array();
foreach ($json_a as $key) {
array_push($arr,json_decode($key[0],true)); //and here you turning each of the JSON-strings into objects themselves
}
$data= 0;
$i=0;
foreach($arr as $element) {
if($data == $element["id"]){
unset($arr[$i]);//removing the product by ID
}
$i++;
}
// print_r($arr);
$arr2 = array();
foreach($arr as $key => $val) {
$arr2[][] = $val;
}
//var_dump($arr2);
echo json_encode($arr2);

php multidimensional array to single dimensional array [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 6 months ago.
I have an array
array(5) {
[0]=>
array(1) {
["id"]=>
string(1) "5"
}
[1]=>
array(1) {
["id"]=>
string(1) "6"
}
[2]=>
array(1) {
["id"]=>
string(1) "7"
}
[3]=>
array(1) {
["id"]=>
string(1) "8"
}
[4]=>
array(1) {
["id"]=>
string(1) "9"
}
}
I wan to make my array like:
$registrationIDs = array( "5","6","7","8","9");
I am trying this code but not working
$results = array();
foreach($result as $inner) {
$results[key($inner)] = current($inner);
}
How do I effeciently transform arrays like this
Try with array_map.
$results = array_map (function ($e) { return $e['id']; }, $inner);
http://php.net/manual/en/function.array-map.php
By the way, if you still want to do it your way, try this form of foreach :
$results = array ();
foreach ($inner as $key => $value)
$results[$key] = $value['id'];
$array = [['id'=>1],['id'=>2],['id'=>3],['id'=>4],['id'=>5],];
$result = call_user_func_array('array_merge_recursive', $array);
var_dump($result['id']);
//array(5) {
// [0] =>
// int(1)
// [1] =>
// int(2)
// [2] =>
// int(3)
// [3] =>
// int(4)
// [4] =>
// int(5)
//}
Ok, I saw a lot of answers, so I wondered what to better answer was.
<?php
$data = array ();
for ($i = 0; $i < 1000000; $i++)
$data[$i] = array ('id' => rand ());
$time0 = microtime (true);
// Niols (1)
$results = array_map (function ($e) { return $e['id']; }, $data);
$time1 = microtime (true);
// Niols (2)
$results = array ();
foreach ($data as $key => $value)
$results[$key] = $value['id'];
$time2 = microtime (true);
// User (1)
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
$results = iterator_to_array($it, false);
$time3 = microtime (true);
// User (2)
$results = array();
foreach ($data as $datum)
$results = array_merge($results, $datum);
$time4 = microtime (true);
// sectus
$results = call_user_func_array('array_merge_recursive', $data);
$time5 = microtime (true);
// Pankaj katiyar and Ghost
$results = array_column($data, 'id');
$time6 = microtime (true);
var_dump ($time1-$time0);
var_dump ($time2-$time1);
var_dump ($time3-$time2);
var_dump ($time4-$time3);
var_dump ($time5-$time4);
var_dump ($time6-$time5);
On my computer, this outputs :
float(0.62708687782288)
float(0.35285401344299)
float(1.5429890155792)
float(0.7408618927002)
float(0.70525908470154)
float(0.15015292167664)
Conclusion :
array_column is ultra-efficient (but PHP 5.5+). Writing a simple foreach seems quite efficient too.
You can try with below code.
I think this is working fine.
Process 1:-
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
$l = iterator_to_array($it, false);
var_dump($l); // one Dimensional
Process 2:-
Try with:
$input = array(/* your array*/);
$output = array();
foreach ( $input as $data ) {
$output = array_merge($output, $data);
}
Try this:
$array = array(/*your array*/);
$results = array();
foreach ($array as $value)
{
foreach($value as $innerValue)
{
$results[] = $innervalue;
}
}

PHP - create dynamic multidimensional file tree array

I want to create a file tree, and for this purpose I need to convert an array of files and directories to a multidimensional file tree array. For example:
array
(
'file.txt',
'dir1/',
'dir1/dir2/',
'dir1/dir2/dir3/',
'dir1/file.txt',
)
to
array
(
'file.txt',
'dir1' =>
array
(
'dir2' =>
array
(
'dir3' =>
array(),
),
'file.txt',
)
)
I've tried several functions to accomplish this, but non of them worked. The problem I've encountered for example that there is no easy way to convert an array ('test','test','test'),'test' to $array['test']['test']['test'] = 'test'.
Here's a shorter recursive one:
function dir_tree($dir) {
$files = array_map('basename', glob("$dir/*"));
foreach($files as $file) {
if(is_dir("$dir/$file")) {
$return[$file] = dir_tree("$dir/$file");
} else {
$return[] = $file;
}
}
return $return;
}
Take a look to my post here.
The answer is: strtok will save you.
<?php
$input = [
'/RootFolder/Folder1/File1.doc',
'/RootFolder/Folder1/SubFolder1/File1.txt',
'/RootFolder/Folder1/SubFolder1/File2.txt',
'/RootFolder/Folder2/SubFolder1/File2.txt',
'/RootFolder/Folder2/SubFolder1/SubSubFolder1/File4.doc',
];
function parseInput($input) {
$result = array();
foreach ($input AS $path) {
$prev = &$result;
$s = strtok($path, '/');
while (($next = strtok('/')) !== false) {
if (!isset($prev[$s])) {
$prev[$s] = array();
}
$prev = &$prev[$s];
$s = $next;
}
$prev[] = $s;
unset($prev);
}
return $result;
}
var_dump(parseInput($input));
Output :
array(1) {
["RootFolder"]=>
array(2) {
["Folder1"]=>
array(2) {
[0]=>
string(9) "File1.doc"
["SubFolder1"]=>
array(2) {
[0]=>
string(9) "File1.txt"
[1]=>
string(9) "File2.txt"
}
}
["Folder2"]=>
array(1) {
["SubFolder1"]=>
array(2) {
[0]=>
string(9) "File2.txt"
["SubSubFolder1"]=>
array(1) {
[0]=>
string(9) "File4.doc"
}
}
}
}
}
I have PHP snippet for that:
<?php
function wps_glob($dir) {
foreach (glob($dir . '/*') as $f) {
if(is_dir($f)) {
$r[] = array(basename($f) => wps_glob($f));
}
else {
$r[] = basename($f);
}
}
return $r;
}
function wps_files($path) {
$wpsdir = Array(
'root' => $path,
'struktur' => wps_glob($path)
);
return $wpsdir;
}
?>
example usage here

Simple PHP Recursion Test Failing

I am attempting a basic recursion to create multi-dimensional arrays based on the values of an inputed array.
The recursion works by checking for a value we shall call it "recursion" to start the loop and looks for another value we'll call it "stop_recursion" to end.
Basically taking this array
array('One', 'Two', 'recursion', 'Three', 'Four', 'Five', 'stop_recursion', 'Six', 'Seven')
And making this array
array('One', 'Two', array('Three', 'Four', 'Five'), 'Six', 'Seven')
The code I have for it so far is as follows
function testRecrusion($array, $child = false)
{
$return = array();
foreach ($array as $key => $value) {
if ($value == 'recursion') {
unset($array[$key]);
$new = testRecrusion($array, true);
$array = $new['array'];
$return[] = $new['return'];
} else {
if ($value == 'stop_recursion') {
unset($array[$key]);
if ($child) {
return array('return' => $return, 'array' => $array);
}
} else {
unset($array[$key]);
$return[] = $value;
}
}
}
return $return;
}
But the output from that is
Array
(
[0] => One
[1] => Two
[2] => Array
(
[0] => Three
[1] => Four
[2] => Five
)
[3] => Three
[4] => Four
[5] => Five
[6] => Six
[7] => Seven
)
I guess the real question is...will an array values continuously loop through the first values given from the initial call or once the new array is returned and set will it loop through that new array. I know the answer is basically right here saying that yes it will continue the old array value, but shouldn't this work vice-versa?
Any help will be appreciated :)
------------ edit -------------------
I might as well add that while I can perform this action using a much simpler method, this needs to be recursively checked since this will be ported to a string parser that could have a infinite number of child arrays.
When you return inside the recursion, you need to return both the inner array and the index from which to continue searching for elements so that you don't look at the same element twice. Try this instead:
function testRecursionImpl($array, $i)
{
$return = array();
for (; $i < sizeof($array); ++$i) {
if ($array[$i] == 'recursion') {
$new = testRecursionImpl($array, $i + 1);
$return[] = $new[0];
$i = $new[1];
} else if ($array[$i] == 'stop_recursion') {
return array($return, $i);
} else {
$return[] = $array[$i];
}
}
return array($return, $i);
}
function testRecursion($array)
{
$result = testRecursionImpl($array, 0);
return $result[0];
}
The problem you have in the code above is that you correctly detect when you should call this function recursively but once it finishes running and you append the results to output array you just pick next element (which is the first element that recursive call will get) and append it to output array. What you probably want to do is when you detect that you should run your function recursively you should skip all other characters until you find your stop word (stop_recursion). Obviously the problem will become harder if you allow multi-level recursion then you may need to even skip some stopwords because they could be from the different level call.
Still I don't know why you want such a feature. Maybe you would explain what are you trying to achieve. I'm pretty sure there's another, simpler way of doing it.
Rather than helping with your homework, I would suggest you start with getting rid of this line:
foreach ($array as $key => $value) {
You should just pass in your array, and check for being at the end of the array, since it can't really be infinite, to know when you are done.
Let me give it a try
function testRecursion($arr){
$return = array();
$recurlevel = 0;
foreach ($arr as $v) {
if($v == 'stop_recursion'){
$recurlevel--;
}
if($recurlevel == 0){
if(isset($current)){
$return[] = testRecursion($current);
unset($current);
}else{
if($v != 'recursion'){
$return[] = $v;
}
}
}else{
if(!isset($current)){
$current = array();
}
$current[] = $v;
}
if($v == 'recursion'){
$recurlevel++;
}
}
return $return;
}
Alright nicely done. This will help even if the recursion and stop_recursion are nested in another. See example:
code.php:
<pre><?php
function testRecursion($arr){
$return = array();
$recurlevel = 0;
foreach ($arr as $v) {
if($v == 'stop_recursion'){
$recurlevel--;
}
if($recurlevel == 0){
if(isset($current)){
$return[] = testRecursion($current);
unset($current);
}else{
if($v != 'recursion'){
$return[] = $v;
}
}
}else{
if(!isset($current)){
$current = array();
}
$current[] = $v;
}
if($v == 'recursion'){
$recurlevel++;
}
}
return $return;
}
$a = array('One', 'Two', 'recursion', 'Three', 'recursion', 'Four' , 'stop_recursion', 'Five', 'stop_recursion', 'Six', 'Seven');
var_dump(testRecursion($a));
?>
Browser output:
array(5) {
[0]=>
string(3) "One"
[1]=>
string(3) "Two"
[2]=>
array(3) {
[0]=>
string(5) "Three"
[1]=>
array(1) {
[0]=>
string(4) "Four"
}
[2]=>
string(4) "Five"
}
[3]=>
string(3) "Six"
[4]=>
string(5) "Seven"
}
Since your question for the recursive solution has already been answered ...might I offer a stack-based solution?
$x = array('a', 'b', 'recursion', 'cI', 'cII', 'cIII', 'recursion', 'cIV1', 'cIV2', 'cIV2', 'stop_recursion', 'stop_recursion', 'd', 'e');
$result = array();
$stack = array(&$result);
foreach($x as $e) {
if ( 'recursion'===$e ) {
array_unshift($stack, array());
$stack[1][] = &$stack[0];
}
else if ( 'stop_recursion'===$e ) {
array_shift($stack);
}
else {
$stack[0][] = $e;
}
}
var_dump($result);
prints
array(5) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
array(4) {
[0]=>
string(2) "cI"
[1]=>
string(3) "cII"
[2]=>
string(4) "cIII"
[3]=>
array(3) {
[0]=>
string(4) "cIV1"
[1]=>
string(4) "cIV2"
[2]=>
string(4) "cIV2"
}
}
[3]=>
string(3) "d"
[4]=>
string(5) "e"
}

Categories